我的问题是,只有当MainRule表具有与Table1表匹配的ID时,此查询才有效。即使MainRule表没有匹配的ID,我也需要查询才能工作。即使在MainRule表中没有匹配的记录,表1中的记录也应该显示。
这是我的代码:
SELECT Person, OrderNum, Name, County, SubmitDate, Days1,
SUM(Date_Diff) - 1 AS [Number of Uncleared Days]
From
(SELECT D1.RecordID AS Person, D3.[case no] AS OrderNum,
D3.FullName AS Name, D3.County, D3.[SignedDate] AS SubmitDate,
DATEDIFF(d, D3.[SignedDate], D3.closedate) AS Days1,
DATEDIFF(DAY, [HoldDate],
(SELECT TOP 1 [StatusDate]
FROM [MainRule] D2
WHERE D2.Status = 'Cleared'
AND D1.RecordID = D2.RecordID
AND D1.StatusDate < D2.StatusDate)) AS [Date_Diff]
FROM [MainRule] AS D1 INNER JOIN table1 AS D3 ON D3.ID = D1.RecordID
WHERE D1.Status = 'UnCleared') SubQ
WHERE (SubmitDate BETWEEN '10/01/2017' and '10/17/2017')
GROUP BY Person, OrderNum, Name, County, SubmitDate, Days1
答案 0 :(得分:2)
只需使用LEFT JOIN
:
SELECT Person, OrderNum, Name, County, SubmitDate, Days1,
SUM(Date_Diff) - 1 AS [Number of Uncleared Days]
From
(SELECT D1.RecordID AS Person, D3.[case no] AS OrderNum,
D3.FullName AS Name, D3.County, D3.[SignedDate] AS SubmitDate,
DATEDIFF(d, D3.[SignedDate], D3.closedate) AS Days1,
DATEDIFF(DAY, [HoldDate],
(SELECT TOP 1 [StatusDate]
FROM [MainRule] D2
WHERE D2.Status = 'Cleared'
AND D1.RecordID = D2.RecordID
AND D1.StatusDate < D2.StatusDate)) AS [Date_Diff]
FROM table1 AS D3
LEFT JOIN [MainRule] AS D1 ON D3.ID = D1.RecordID
WHERE D1.Status = 'UnCleared') SubQ
WHERE (SubmitDate BETWEEN '10/01/2017' and '10/17/2017')
GROUP BY Person, OrderNum, Name, County, SubmitDate, Days1
这样,即使另一个表MainRule
中没有匹配的行,您也会从table1
(左表)中获取所有行。
您应该阅读有关联接类型之间差异的更多信息:
答案 1 :(得分:0)
您有两个问题:INNER JOIN
(正如其他答案所解释的)和WHERE D1.Status = 'UnCleared'
。
无论您的联接是什么,WHERE
子句将排除没有匹配的MainRule行的行。
尝试类似WHERE D1.Status = 'UnCleared' OR D1.Status IS NULL
的内容。