MySQL query to return multiple summed columns

Deadly 提交于 2019-12-24 16:23:02

问题


I have the following data in my SQL table.

uid    user    category    count    date
--------------------------------------------------
1      henry   RED         4        2013-05-01
2      john    BLUE        3        2013-05-01
3      alice   RED         5        2013-05-01
4      eric    GREEN       2        2013-05-02
5      eric    BLUE        2        2013-05-02
6      john    RED         3        2013-05-02
7      henry   GREEN       2        2013-05-02
8      eric    RED         3        2013-05-03
9      john    BLUE        5        2013-05-03

I would like a query that gives me back the following data

category    2013-05-01    2013-05-02    2013-05-03
---------------------------------------------------
RED         9             3             3
BLUE        3             2             5
GREEN       0             4             0

I can get one column of data with the following query, but I do not know how to get multiple columns grouped as shown above. I'd like to have one query that my PHP renders instead of looping through each date.

SELECT category, SUM(count) 
FROM dbtable 
WHERE date='2013-05-01' 
GROUP BY category;

Is this possible? Ideas?


回答1:


Something like this should work:

SELECT
  category,
  SUM(CASE WHEN date = '2013-05-01' THEN count END) AS `2013-05-01`,
  SUM(CASE WHEN date = '2013-05-02' THEN count END) AS `2013-05-02`,
  SUM(CASE WHEN date = '2013-05-03' THEN count END) AS `2013-05-03`
FROM dbtable
GROUP BY category


来源:https://stackoverflow.com/questions/17323507/mysql-query-to-return-multiple-summed-columns

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!