如果没有与日期匹配的记录,我想显示空记录。
如果你想包含 NULL 值,那么你可能需要一个 LEFT OUTER JOIN(或只是“LEFT JOIN”):
SELECT a.RacLetterId, a.AppealsLevelId, b.AppealLevelId, a.Level, a.DateSent, a.DeliveryService, b.AppealOutcomeId, b.AppealOutcomeDate
FROM dbo.tbl_Tab_AppealsLevel a
LEFT JOIN
(
SELECT AppealLevelId, AppealOutcomeId,AppealOutcomeDate
FROM dbo.tbl_Tab_AppealCode
WHERE AppealLevel = 1
) b
ON (AppealLevelId = a.AppealsLevelId)
WHERE Level = 1
有关连接的更多信息,我推荐 Jeff Atwoord 的CODING HORROR: A Visual Explanation of SQL Joins
我想显示最近的 AppealOutcomeDate。
如果日期是重复项中唯一具有更改值的列,那么您可以GROUP BY
在所有其他列上使用简单的并选择MAX(AppealOutcomeDate)
SELECT a.RacLetterId, a.AppealsLevelId, b.AppealLevelId, a.Level, a.DateSent, a.DeliveryService, b.AppealOutcomeId, MAX(b.AppealOutcomeDate)
FROM dbo.tbl_Tab_AppealsLevel a
LEFT JOIN
(
SELECT AppealLevelId, AppealOutcomeId,AppealOutcomeDate
FROM dbo.tbl_Tab_AppealCode
WHERE AppealLevel = 1
) b
ON (AppealLevelId = a.AppealsLevelId)
WHERE Level = 1
GROUP BY a.RacLetterId, a.AppealsLevelId, b.AppealLevelId, a.Level, a.DateSent, a.DeliveryService, b.AppealOutcomeId
如果其他列的值正在更改(与更改日期相关),并且是导致重复数据的连接,那么您可以在 JOIN 的 ON 子句中添加子查询:
SELECT a.RacLetterId, a.AppealsLevelId, b.AppealLevelId, a.Level, a.DateSent, a.DeliveryService, b.AppealOutcomeId, b.AppealOutcomeDate
FROM dbo.tbl_Tab_AppealsLevel a
LEFT JOIN
(
SELECT AppealLevelId, AppealOutcomeId,AppealOutcomeDate
FROM dbo.tbl_Tab_AppealCode
WHERE AppealLevel = 1
) b
ON AppealLevelId = a.AppealsLevelId
AND AppealOutcomeDate =
(
SELECT MAX(AppealOutcomeDate)
FROM dbo.tbl_Tab_AppealCode
WHERE AppealLevel = 1
AND AppealLevelId = a.AppealsLevelId
)
WHERE Level = 1