我有以下查询,我需要与同一天具有相同golddate的用户数量的计数,但是由于我必须使用GROUP BY,当那天没有人时它不会返回零值你能帮忙吗?
SELECT count( * ) AS total, DATE( `golddate` ) AS gold_date
FROM `user`
WHERE YEAR( `golddate` ) >=2014
GROUP BY DATE( `golddate` )
ORDER BY DATE( `golddate` ) ASC
我想展示类似
的内容goldate | total
2012-12-10 | 23
2012-10-12 | 0
但问题是它永远不会返回零值日期,因为
分组我试过以下但没有用,
SELECT
u1.golddate
-- this will count the number of links to each word
-- if there are no links the COUNT() call will return 0
, COUNT(u2.golddate) AS linkCount
FROM user u2
LEFT JOIN user u1
ON u1.user_id = u2.user_id
OR u2.user_id = u1.user_id
GROUP BY u1.golddate
这甚至不起作用
SELECT COALESCE(COUNT(`golddate`), 0) AS total, DATE( `golddate` ) AS gold_count
FROM `user`
WHERE YEAR( `golddate` ) >=2014
GROUP BY DATE( `golddate` )
ORDER BY DATE( `golddate` ) ASC
答案 0 :(得分:1)
正如其他人所提到的,您需要人为地创建缺失数据的日期。
使用RedFilter's cross join date generation code here,您可以在此处创建给定范围内的所有日期,然后将LEFT JOIN返回到您的实际数据。 COUNT(*)需要更改为user
表中的某些内容,以便不计算虚拟日期。
SELECT count(u.golddate) AS total, a.Date AS golddate
FROM
(
select curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY as Date
from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a
cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b
cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c
) a
LEFT OUTER JOIN `user` u
ON DATE(u.golddate) = a.Date
WHERE a.Date between '2013-01-01' and '2013-01-10'
GROUP BY a.Date
ORDER BY a.Date ASC;