我有两张桌子。第一个包含有关小时的信息:
ID | activitydate | userid | phaseid | activityid | time |
3 | 2011-04-11 | 1 | 1 | 1 | 120 |
4 | 2011-04-12 | 1 | 1 | 1 | 180 |
5 | 2011-04-12 | 3 | 1 | 1 | 360 |
6 | 2011-04-22 | 2 | 2 | 3 | 300 |
保存用户数据的第二个表:
ID | userid | lastname |
1 | abc | ABC |
2 | xyz | XYZ |
3 | asd | ASD |
4 | qwe | QWE |
我需要一个生成以下格式的查询:
Date | ABC | XYZ | ASD | QWE |
2011-04-11 | 120 | 0 | 0 | 0 |
2011-04-12 | 180 | 0 | 360 | 0 |
2011-04-22 | 0 | 300 | 0 | 0 |
这可以是以下格式:
User | 2011-04-11 | 2011-04-12 | 2011-04-13| .... | 2011-04-22 |...
ABC | 120 | 180 | 0 | .....| 0 |...
XYZ | 0 | 0 | 0 | .....| 300 |...
ASD | 0 | 360 | 0 | .....| 0 |...
QWE | 0 | 0 | 0 | .....| 0 |...
非常感谢任何帮助!
答案 0 :(得分:0)
这样做:
SELECT
u.lastname AS `User`
, SUM(CASE WHEN activitydate='2011-04-01' THEN time ELSE 0 END) AS `2011-04-01`
, SUM(CASE WHEN activitydate='2011-04-02' THEN time ELSE 0 END) AS `2011-04-02`
, ...
, SUM(CASE WHEN activitydate='2011-04-30' THEN time ELSE 0 END) AS `2011-04-30`
FROM Hours h
JOIN Users u
ON h.userid = u.userid
WHERE h.activitydate BETWEEN '2011-04-01' AND '2011-04-30'
GROUP BY h.userid
ORDER BY h.userid