Mysql 使用GROUP BY为多个值填写缺少的日期
我试图编写一个查询,用于检索日期范围内多个用户的时间信息 我的表格设置如下: 条目:Mysql 使用GROUP BY为多个值填写缺少的日期,mysql,sql,gaps-and-islands,Mysql,Sql,Gaps And Islands,我试图编写一个查询,用于检索日期范围内多个用户的时间信息 我的表格设置如下: 条目: user_id | entry_date | entry_hours 1 | 2013-11-12 | 4 1 | 2013-11-12 | 5 1 | 2013-11-13 | 3 2 | 2013-11-13 | 7 .... 日历: calendar_date ..... 2013-11-10 2013-11-11 2013-11-12
user_id | entry_date | entry_hours
1 | 2013-11-12 | 4
1 | 2013-11-12 | 5
1 | 2013-11-13 | 3
2 | 2013-11-13 | 7
....
日历:
calendar_date
.....
2013-11-10
2013-11-11
2013-11-12
2013-11-13
2013-11-14
.....
如果我运行此查询:
SELECT *, e.user_id, e.entry_date, COALESCE(SUM(e.entry_hours), 0) as total
FROM `entry` e
WHERE entry_date BETWEEN '2013-11-12' and '2013-11-13'
GROUP BY e.user_id, e.entry_date
我得到了一些有影响的东西
user_id | entry_date | total
1 | 2013-11-12 | 9
1 | 2013-11-13 | 3
2 | 2013-11-13 | 7
当我想要这个的时候:
user_id | entry_date | total
1 | 2013-11-12 | 9
1 | 2013-11-13 | 3
2 | 2013-11-12 | 0
2 | 2013-11-13 | 7
其中,它用0填充缺少的日期
编辑:当用户没有列出的条目时,我还需要它拉入具有0的用户id。假设我包含在那里WHERE
子句中,并且用户id包含在(1,2,3)
中,我会得到如下结果:
user_id | entry_date | total
1 | 2013-11-12 | 9
1 | 2013-11-13 | 3
2 | 2013-11-12 | 0
2 | 2013-11-13 | 7
3 | 2013-11-12 | 0
3 | 2013-11-13 | 0
日历表背后的想法是能够提取一个范围内的所有日期,并将它们与条目表连接起来,以填充那些缺少的日期,但我一直无法想出如何做到这一点
有人能给我指出正确的方向吗?我知道我在原来的帖子里忘了什么——请看我的编辑。我还需要它填充0,其中where子句中提供了用户\u id,但表中没有该用户的条目。您需要一个单独的表来列出您的用户,就像日历一样。我确实有一个包含用户\u id的用户表--我是否也需要加入该表?是的。你的成绩中的一切都必须来自某个地方。如果希望条目表中缺少用户标识,则需要引入一个包含这些标识的表。
SELECT
u.user_id,
c.calendar_date,
COALESCE(SUM(e.entry_hours), 0)
FROM calendar c
CROSS JOIN users u
LEFT JOIN entry e
ON (c.calendar_date = e.entry_date AND u.user_id = e.user_id)
GROUP BY u.user_id,c.calendar_date