MySQL:在同一个字段上具有不同WHERE的多个SELECT,导致单独的列

时间:2018-02-21 18:18:46

标签: mysql sql

我已经阅读了很多关于类似情况的问题,但似乎找不到解决方案。

我有以下查询来获取每个用户每个日历周的累计时间跟踪(停止和启动是UNIX时间戳),按时间跟踪类型(项目时间,驾驶时间等)分开。

SELECT 
u.login as Person,
DATE_FORMAT(FROM_UNIXTIME(t.start), '%x-%v') as CalendarWeek,
t.tracking_type as TrackingType,
REPLACE(ROUND(SUM(stop-start) / 60 / 60, 2), '.', ',') AS TimeHrs
FROM ps_time_tracking t
LEFT OUTER JOIN users u ON (u.id = t.user_id)
GROUP BY Person, CalendarWeek, TrackingType
ORDER BY CalendarWeek ASC, Person ASC

结果如下:

| Person | CalendarWeek | TrackingType | TimeHrs | 
| ------------------------------------------------
| User A | 2018-01      | project time | 31,82   | 
| User A | 2018-01      | driving time | 4,75    | 
| User B | 2018-01      | project time | 60,17   | 
| User B | 2018-01      | driving time | 9,02    | 
| User C | 2018-01      | project time | 7,33    |

目标是将多个WHERE的结果放在

WHERE t.tracking_type = 'project time'
WHERE t.tracking_type = 'driving time'

在不同的结果列中:

| Person | CalendarWeek | TrackingType | ProjectTime | DrivingTime |
| --------------------------------------------------------------------
| User A | 2018-01      | project time | 31,82       | 4,75        |
| User B | 2018-01      | project time | 60,17       | 9,02        |
| User C | 2018-01      | project time | 7,33        | (null)      |

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

您可以使用CASE来获取所需内容。它看起来像这样:

SELECT 
u.login as Person,
DATE_FORMAT(FROM_UNIXTIME(t.start), '%x-%v') as CalendarWeek,
REPLACE(ROUND(SUM(CASE WHEN TrackingType = 'project time' THEN stop-start ELSE 0 END) / 60 / 60, 2), '.', ',') AS ProjectTime,
REPLACE(ROUND(SUM(CASE WHEN TrackingType = 'driving time' THEN stop-start ELSE 0 END) / 60 / 60, 2), '.', ',') AS DrivingTime
FROM ps_time_tracking t
LEFT OUTER JOIN users u ON (u.id = t.user_id)
GROUP BY Person, CalendarWeek
ORDER BY CalendarWeek ASC, Person ASC