分组后获取最新记录信息

(1)

Select * From TABLE_NAME_MessageGroup G Inner Join
(select *
from TABLE_NAME_MessageDetail D
where
group_type
in
(
select group_type from TABLE_NAME_MessageDetail t where
send_time=(select max(send_time) from TABLE_NAME_MessageDetail t1 where t1.group_type=t.group_type)
group by group_type
)
and send_time=(select max(send_time) from TABLE_NAME_MessageDetail t1 where t1.group_type=D.group_type)) D1 On G.group_type=D1.group_type
Inner Join (Select group_type,count(*) As UnReadCount From TABLE_NAME_MessageDetail Group By group_type) R On R.group_type=G.group_type
Where G.belongs=''
order By D1.send_time Desc

TABLE_NAME_MessageGroup 是parent table,TABLE_NAME_MessageDetail 是child table,按照send_time 排序获取最新记录

(2) 使用 row_numbere() Over

Select * From TABLE_NAME_MessageGroup G Inner Join
(Select * From
(Select id,belongs,group_type,send_time,title,content, ROW_NUMBER() over(partition by group_type order by send_time desc) As XY_C From TABLE_NAME_MessageDetail)T
Where T.XY_C<2) D1 On G.group_type=D1.group_type
Inner Join (Select group_type,count(*) As UnReadCount From TABLE_NAME_MessageDetail Group By group_type) R On R.group_type=G.group_type
order By D1.send_time Desc

按照逻辑排序完了以后,取排序过的第一条数据的信息

原文地址:https://www.cnblogs.com/zcwfb/p/15396839.html