Mysql query two tables & get data in date wise or user wise
I have two tables. The first one holds information about Hours:
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 |
The 2nd table holding the data of Users:
ID | userid | lastname |
1 | abc | ABC |
2 | xyz | XYZ |
3 | asd | ASD |
4 | qwe | QWE |
I need a query which generate below given format:
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 |
This can be as below format:
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 |...
Any help is really appreciated!
This would do:
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
精彩评论