按日期和价值分组

时间:2013-01-25 11:37:35

标签: php mysql

我在一个名为articles的表格中有4列:created_at,文章,关键字和类别

我有这个查询来分析数据:

SELECT DATE(`created_at`) AS date, COUNT(1) AS articles 
FROM articles 
WHERE `keyword`='keyword1' 
GROUP BY DATE(`created_at`)

这会返回一个关键字每天的文章总数。

我希望有一个总数,然后将其分解,并将文章归类为每个关键字cat1cat2cat3。所以给出一个这样的表:

|date|keyword|articles|cat1|cat2|cat3| 

我似乎无法做到这一点,所以任何帮助都会受到赞赏!

1 个答案:

答案 0 :(得分:2)

select 
DATE(`created_at`),
keyword,
count(*) as TotalCount,
SUM (case when Category = Cat1 then 1 else 0 end) as Cat1Count,
SUM (case when Category = Cat2 then 1 else 0 end) as Cat2Count,
SUM (case when Category = Cat3 then 1 else 0 end) as Cat3Count

from articles
group by DATE(`created_at`), keyword
order by DATE(`created_at`), keyword