查询表:复杂连接

时间:2016-08-18 01:23:47

标签: sql sql-server join

我有这个查询,当表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

2 个答案:

答案 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