如何有效地改进我的查询

时间:2018-04-18 02:35:04

标签: mysql sql

我是MySQL的新手。

我正在尝试使用DATE数据进行统计。

enter image description here

我希望看到的输出是

enter image description here

我的查询

SELECT 
    (SELECT count(user_id)
     FROM MYTABLE
     WHERE cr_dt > '2018-04' AND cr_dt < '2018-05'
    ) AS April,
    (SELECT count(user_id)
     FROM MYTABLE
     WHERE cr_dt > '2018-03' AND cr_dt < '2018-04'
    ) AS March,
    (SELECT count(user_id)
     FROM MYTABLE
     WHERE cr_dt > '2018-02' AND cr_dt < '2018-03'
    ) AS Febrary
FROM MYTABLE;

和我的输出

enter image description here

1 个答案:

答案 0 :(得分:2)

使用条件聚合:

SELECT SUM(cr_dt > '2018-04' AND cr_dt < '2018-05') as April,
       SUM(cr_dt > '2018-03' AND cr_dt < '2018-04') as March,
       SUM(cr_dt > '2018-02' AND cr_dt < '2018-03') as February
FROM MYTABLE;

这假定user_id永远不会NULL。您可以考虑到这一点:

SELECT SUM(cr_dt > '2018-04' AND cr_dt < '2018-05') as April,
       SUM(cr_dt > '2018-03' AND cr_dt < '2018-04') as March,
       SUM(cr_dt > '2018-02' AND cr_dt < '2018-03') as February
FROM MYTABLE
WHERE user_id IS NOT NULL;

我不会为此目的使用部分日期。我会把它写成:

SELECT SUM(cr_dt >= '2018-04-01' AND cr_dt < '2018-05-01') as April,
       SUM(cr_dt >= '2018-03-01' AND cr_dt < '2018-04-01') as March,
       SUM(cr_dt >= '2018-02-01' AND cr_dt < '2018-03-01') as February
FROM MYTABLE
WHERE user_id IS NOT NULL;