得到最后一行?

时间:2013-11-22 15:57:23

标签: sql sql-server

我有下表(表格称为帖子):

id  datecreated                 threadid
1   2013-03-17 17:36:12.9281661 1
2   2013-03-17 17:56:18.3472836 1
3   2013-03-18 07:09:08.2733381 2
4   2013-03-18 07:35:58.1251661 3
5   2013-03-18 22:04:41.6053307 3
6   2013-03-19 03:30:56.0803165 3
7   2013-03-19 16:26:59.1518276 4
8   2013-03-19 16:27:47.4339124 4
9   2013-03-19 16:28:13.3455579 4
10  2013-03-19 16:55:16.3930089 5

我希望查询只返回三次列出threadid的行,但我只想要每个threadid的一行,并且它需要是最后一行(按日期排序)。

我该怎么做?

2 个答案:

答案 0 :(得分:4)

select p.*
from posts p
inner join
(
  select threadid, max(datecreated) maxdate 
  from posts
  group by threadid
  having count(*) = 3
) x on x.threadid = p.threadid and x.maxdate = p.datecreated

答案 1 :(得分:4)

您可以使用排名功能:

WITH CTE AS
(
    SELECT id, datecreated, threadid,
        TotalCount = COUNT(*) OVER (PARTITION BY threadid),
        RN = ROW_NUMBER()     OVER (PARTITION BY threadid
                                    ORDER BY datecreated DESC)
    FROM dbo.Posts
)
SELECT id, datecreated, threadid
FROM CTE 
WHERE TotalCount = 3 AND RN = 1

Sql-Fiddle