0

我遇到了一个 SQL 问题。我收到重复的记录。由于日期不同,我也收到了多条记录。以下是数据示例:

示例 SQL 数据

这是我的 SQL:

SELECT a.RacLetterId, a.AppealsLevelId, b.AppealLevelId, a.Level, a.DateSent, a.DeliveryService, b.AppealOutcomeId, b.AppealOutcomeDate
FROM dbo.tbl_Tab_AppealsLevel a
INNER JOIN (
    SELECT AppealLevelId, AppealOutcomeId,AppealOutcomeDate
    FROM dbo.tbl_Tab_AppealCode
    WHERE AppealLevel = 1
    ) b
ON (AppealLevelId = a.AppealsLevelId)
WHERE Level = 1

如果没有与日期匹配的记录,我想显示空记录。除此之外,我想展示最新的AppealOutcomeDate.

4

2 回答 2

0

如果没有与日期匹配的记录,我想显示空记录。

如果你想包含 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
于 2013-10-23T15:18:46.000 回答
0

改用 LEFT JOIN 以便您可以包含空行,并且您可以使用 NOT EXISTS 子句来消除除最大日期记录之外的所有记录:

SELECT a.RacLetterId, a.AppealsLevelId, b.AppealLevelId, a.Level, a.DateSent,
    a.DeliveryService, b.AppealOutcomeId, b.AppealOutcomeDate
FROM dbo.tbl_Tab_AppealsLevel a
LEFT OUTER JOIN dbo.tbl_Tab_AppealCode b ON a.AppealsLevelId = b.AppealLevelId
    AND b.AppealLevel = 1
WHERE a.Level = 1
AND NOT EXISTS
(
    SELECT 1
    FROM dbo.tbl_Tab_AppealCode bb
    WHERE bb.AppealLevelId = b.AppealLevelId
    AND bb.AppealLevel = 1
    AND bb.AppealOutcomeDate > b.AppealOutcomeDate
)
于 2013-10-23T15:19:00.340 回答