如何在摘要查询中包含记录以包括那些没有数据的记录?

时间:2018-04-04 15:24:22

标签: sql sql-server relational-database

我在事务表上有一个查询,它根据数据范围为每个ID返回一列的Summarized总数。查询工作正常,但不包括那些在事务表中没有数据的ID。如何在填充总计为零的结果中包含这些ID。这是我的查询的简化版本。

SELECT tblID.IDName
    ,SUM(CASE 
            WHEN tblTransactions.idxTransType = 30
                THEN CAST(tblTransactions.TimeAmount AS FLOAT) / 60.0
            ELSE 0
            END) AS 'Vacation'
FROM tblTransactions
INNER JOIN tblTransTypes ON tblTransactions.idxTransType = tblTransTypes.IdxTransType
INNER JOIN tblID ON tblTransactions.idxID = tblID.IdxID
WHERE (tblTransactions.Deleted = 0)
    AND (tblTransactions.NotCurrent = 0)
    AND (tblTransactions.TransDate >= CONVERT(DATETIME, 'March 1, 2018', 102))
    AND (tblTransactions.TransDate <= CONVERT(DATETIME, 'April 11, 2018', 102))
GROUP BY tblID.IDName

2 个答案:

答案 0 :(得分:0)

您需要left join s:

SELECT i.IDName, 
       SUM(CASE WHEN t.idxTransType = 30 THEN CAST(t.TimeAmount AS Float) / 60.0 ELSE 0 END) AS Vacation
FROM tblID i LEFT JOIN
     tblTransactions t
     ON t.idxID = i.IdxID AND
        t.Deleted = 0 AND 
        t.NotCurrent = 0 AND
        t.TransDate >= '2018-03-01' AND
        t.TransDate <= '2018-04-11'
     tblTransTypes tt
     ON t.idxTransType = tt.IdxTransType 
GROUP BY i.IDName;

注意:

  • 表别名使查询更容易编写和阅读。
  • 使用ISO / ANSI标准日期格式。
  • 除第一个表外的所有表的过滤条件都属于ON子句。

答案 1 :(得分:0)

实际上它稍微复杂一点:

SELECT        
    i.IDName, 
    SUM(CASE WHEN t.idxTransType = 30 THEN CAST(t.TimeAmount AS FLOAT) / 60.0 ELSE 0 END) AS 'Vacation'
FROM
    tblID i
    LEFT JOIN tblTransactions t ON t.idxID = i.IdxID AND t.Deleted = 0 AND t.NotCurrent = 0 AND t.TransDate BETWEEN '20180301' AND '20180411'
    LEFT JOIN tblTransTypes tt ON tt.IdxTransType = t.idxTransType
GROUP BY 
    i.IDName;