我是MySQL
的新手。
我正在尝试使用DATE
数据进行统计。
我希望看到的输出是
我的查询
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;
和我的输出
答案 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;