我有以下sql查询
SELECT DATE_FORMAT(date,'%d.%m. %y') as date, COUNT(idStat) as number
FROM stat
WHERE IdGame = ? AND date >= ? AND date <= ?
GROUP BY date
它返回日期以及今天有多少人访问了游戏,但是当今天没有行时如何返回0?
例如,db 12中不存在日期12.12.1993,但用户选择日期为15.10.1950和12.15.2020之间。
我想返回这个不存在的日期15.12.1993,但计数为0。 这甚至可能吗?
感谢您的帮助,
菲利普。
答案 0 :(得分:5)
最好的方法是使用Calendar
表格,并附上相关日期。然后,您可以使用left join
来获取日期。像这样:
SELECT DATE_FORMAT(c.date,'%d.%m. %y') as date, COUNT(s.idStat) as number
FROM Calendar c LEFT JOIN
stat s
ON c.date = s.date AND s.IdGame = ?
WHERE c.date >= ? AND c.date <= ?
GROUP BY c.date;
如果你在每个日期都有游戏,但问题是特定的游戏不是当天的游戏,你可以使用这个捷径:
SELECT DATE_FORMAT(date,'%d.%m. %y') as date, SUM(IdGame = ?) as number
FROM stat
WHERE date >= ? AND date <= ?
GROUP BY date;
这在所有情况下都不起作用,但它可以是一个有用的捷径。
答案 1 :(得分:0)
我使用RedFilter Answer来解决我的问题,来自以下链接:generate days from date range
我的查询现在看起来像这样:
select DATE_FORMAT(a.Date,'%d.%m. %Y'), COUNT(stat.IdStat)
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
) as a LEFT JOIN stat ON a.Date = stat.date
where a.Date between ? and ? AND (stat.IdGame = ? OR stat.IdGame IS NULL) GROUP BY a.Date
但是我需要从我的datapicker中删除未来的日期,因为当我在这个sql中使用futue日期时,没有数据会返回...我需要设置我的datapicker的最小值和最大值。