我有一张表,其中包含大量花费的小时数。我试图根据日期的特定特征获得花费的小时数。我的查询将与此任务竞争,但如果某个特定日期的特定特征集没有值,则该日期不会返回任何数据。我知道如果我用不同的连接类型加入表时如何解决这个问题,但是当连接在where语句中时我不知道如何做到这一点。
SELECT
t1.dates,
t1.hours1,
t2.hours2,
t3.hours3,
t4.hours4
FROM
(
SELECT
dates,
SUM(times) AS hours1
FROM mytable
WHERE
characterisics1
GROUP By dates
) t1,
(
SELECT
dates,
SUM(times) AS hours2
FROM mytable
WHERE
characterisics2
GROUP By dates
) t2,
(
SELECT
dates,
SUM(times) AS hours3
FROM mytable
WHERE
characterisics3
GROUP By dates
) t3,
(
SELECT
dates,
SUM(times) AS hours4
FROM mytable
WHERE
characterisics4
GROUP By dates
) t4
WHERE
t1.dates = t2.dates and t1.dates = t3.dates and t1.dates = t4.dates
ORDER BY
t1.dates DESC
答案 0 :(得分:3)
使用条件聚合。 。 。这么简单:
SELECT dates,
SUM(CASE WHEN characterisics1 THEN times ELSE 0 END) AS hours1,
SUM(CASE WHEN characterisics2 THEN times ELSE 0 END) AS hours2,
SUM(CASE WHEN characterisics3 THEN times ELSE 0 END) AS hours3,
SUM(CASE WHEN characterisics4 THEN times ELSE 0 END) AS hours4,
SUM(CASE WHEN characterisics5 THEN times ELSE 0 END) AS hours5
FROM mytable
GROUP By dates;