将我的SQL下载到最新的记录

时间:2013-10-23 15:13:03

标签: sql sql-server-2008

我遇到了SQL问题。我正在获取重复记录。由于日期不同,我也得到了多条记录。以下是数据示例:

Sample SQL Data

这是我的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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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
)