按日期和Case语句分组的SQL语法

时间:2017-04-24 03:30:16

标签: mysql group-by case

我的mysql数据库类似于以下内容,并且正在努力正确使用case,group by和order by语句。样本数据集:

ID     Date          Direction
1      2017-04-01    1
2      2017-04-01    1
3      2017-04-01    -1
4      2017-04-01    1
5      2017-04-01    -1
6      2017-04-01    1
7      2017-04-02    -1
8      2017-04-02    -1
9      2017-04-02    -1
10     2017-04-02    1
11     2017-04-02    -1
12     2017-04-03    -1

我试图了解聚合此表和按日期分组的最佳方法,以便查询返回以下记录集。 "积极"下面的列只是方向列(上面)的计数,其中方向>同样,"否定" column是方向列的计数,其中方向< 0喜欢这样:

DATE         positive      negative   
2017-04-01   4             2
2017-04-02   1             4
2017-04-03   0             1

我试过了:

 SELECT DATE, 
        CASE
            WHEN direction < 0 THEN 'negative'
            WHEN direction > 0 THEN 'positive'
        END AS updownType, count(*) AS updownCount
        FROM table WHERE DATE BETWEEN '2017-04-01' AND '2017-04-03'
        GROUP BY DATE, updownType
        ORDER BY DATE ASC

我已经回顾了很多关于这个主题的SO主题,但是还没有找到我正在寻找的东西。任何建议表示赞赏

1 个答案:

答案 0 :(得分:1)

哎呀,你错过了。见下文

SELECT DATE, 
        count(CASE WHEN direction < 0 THEN '1' END) AS negative,
        Count(CASE WHEN direction > 0 THEN '1' END) AS positive 
        FROM table WHERE DATE BETWEEN '2017-04-01' AND '2017-04-03'
        GROUP BY DATE
        ORDER BY DATE ASC