我有这个查询,当表Tiempo
上有匹配的行时它做得很好。
问题在于,我真正需要看到的是Tiempo
中不匹配的行,也存在于Usuario
中。
SELECT u.Id, t.empleado, CAST(MONTH(t.fecha) AS VARCHAR(2)) AS MonthNumber, CAST(YEAR(t.fecha) AS VARCHAR(4)) AS YearNumber, SUM(t.horas) AS Horas
FROM Usuario u
INNER JOIN Tiempo t ON u.username = t.empleado
WHERE fecha >= '2016-08-01' and fecha <= '2016-08-31'
GROUP BY u.id, t.empleado, CAST(MONTH(t.fecha) AS VARCHAR(2)), CAST(YEAR(t.fecha) AS VARCHAR(4))
这是输出:
Id empleado MonthNumber YearNumber Horas
86 username1 8 2016 96
95 username2 8 2016 80
99 username3 8 2016 47
102 username4 8 2016 85
这就是我正在寻找的:
Id empleado MonthNumber YearNumber Horas
86 username1 8 2016 96
95 username2 8 2016 80
99 username3 8 2016 47
102 username4 8 2016 85
102 username5 8 2016 null (or 0)
编辑:示例数据:download
答案 0 :(得分:3)
假设您的表中存在缺失行的数据,则执行LEFT JOIN
而不是INNER JOIN
:
SELECT u.Id,
COALESCE(t.empleado, 'NA')
COALESCE(CAST(MONTH(t.fecha) AS VARCHAR(2)), 'NA') AS MonthNumber,
COALESCE(CAST(YEAR(t.fecha) AS VARCHAR(4)), 'NA') AS YearNumber,
SUM(t.horas) AS Horas
FROM Usuario u
LEFT OUTER JOIN Tiempo t
ON u.username = t.empleado AND
fecha >= '2016-08-01' AND
fecha <= '2016-08-31'
GROUP BY u.id,
t.empleado,
CAST(MONTH(t.fecha) AS VARCHAR(2)),
CAST(YEAR(t.fecha) AS VARCHAR(4))
答案 1 :(得分:0)
你想要on
,但你必须要小心。 second 表中的条件需要在SELECT u.Id, t.empleado, CAST(MONTH(t.fecha) AS VARCHAR(2)) AS MonthNumber,
CAST(YEAR(t.fecha) AS VARCHAR(4)) AS YearNumber,
SUM(t.horas) AS Horas
FROM Usuario u LEFT JOIN
Tiempo t
ON u.username = t.empleado AND
t.fecha >= '2016-08-01' AND t.fecha <= '2016-08-31'
GROUP BY u.id, t.empleado, CAST(MONTH(t.fecha) AS VARCHAR(2)), CAST(YEAR(t.fecha) AS VARCHAR(4))
子句中:
rake tmp:clear