如何从3组返回的行中获取最后一个ID?

时间:2014-06-10 10:44:04

标签: sql sql-server-2008-r2

伙计我有一个简单的查询,它从表Notice返回3行(部门名称的Department表上的内连接)除了3个最新行(基于通知的发布日期)

这是查询:

SELECT TOP (3) n.NoticeID, 
    [Subject],
    n.IssueDate,
    d.DepartName AS 'Department',
    n.Body, 
    n.NoticeImage, 
    n.Icon 
FROM dbo.Notice n INNER JOIN dbo.Department d ON  d.DepartmentID = n.DepartmentID
WHERE n.NoticeID NOT IN (SELECT TOP 3 n.NoticeID FROM dbo.Notice n INNER JOIN 
dbo.Department d ON d.DepartmentID = n.DepartmentID
ORDER BY IssueDate DESC) ORDER BY n.IssueDate DESC

现在我要做的是,获取返回的最后一行的NoticeID .. 例如,如果返回的Data有3行,其中NoticeID为25,24,21 ......我想从查询中获取NoticeID = 21(返回的最后一行的NoticeID)。我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以进行子查询以获取最后一个NoticeID,如下所示

Select Min(NoticeiID) From
(
SELECT TOP (3) n.NoticeID, 
    [Subject],
    n.IssueDate,
    d.DepartName AS 'Department',
    n.Body, 
    n.NoticeImage, 
    n.Icon 
FROM dbo.Notice n INNER JOIN dbo.Department d ON  d.DepartmentID = n.DepartmentID
WHERE n.NoticeID NOT IN (SELECT TOP 3 n.NoticeID FROM dbo.Notice n INNER JOIN 
dbo.Department d ON d.DepartmentID = n.DepartmentID
ORDER BY IssueDate DESC) ORDER BY n.IssueDate DESC
) as T1