sql - 获取最后一个不同的行?

标签 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 的一行,并且它必须是最后一行(按日期排序)。

我该怎么做?

最佳答案

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

关于sql - 获取最后一个不同的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20149128/

相关文章:

sql - 从数据中删除斜线并在 sql server 的选择查询中创建新字段

sql - 如何 - 在 SQL Server 中创建后直接创建和使用数据库?

sql - select_list : Only take some columns 中的条件

sql - 使用 select 语句在创建表语法中定义默认列值

mysql - SQL 内部连接多列

php - 仅当字符串不为空时才执行查询

sql-server - 关闭隐式事务

sql-server - 基于 If then Else sql server 2008 将默认值添加到现有列

php - 从MySQL表中获取特定数据

c# - 在 NHibernate 中调用 Named Query 并将参数传递给 Sybase Server