我需要通过查询编写一个包含多个日期和seq列的表的T-SQL组:
DROP TABLE #temp
CREATE TABLE #temp(
id char(1),
dt DateTime,
seq int)
Insert into #temp values('A','2015-03-31 10:00:00',1)
Insert into #temp values('A','2015-08-31 10:00:00',2)
Insert into #temp values('A','2015-03-31 10:00:00',5)
Insert into #temp values('B','2015-09-01 10:00:00',1)
Insert into #temp values('B','2015-09-01 10:00:00',2)
我希望结果只包含项目A,B及其最新日期和对应的序列号,例如:
id MaxDate CorrespondentSeq
A 2015-08-31 10:00:00.000 2
B 2015-09-01 10:00:00.000 2
我正在尝试(显然是错误的!):
select id, max(dt) as MaxDate, max(seq) as CorrespondentSeq
from #temp
group by id
返回:
id MaxDate CorrespondentSeq
A 2015-08-31 10:00:00.000 5 <-- 5 is wrong
B 2015-09-01 10:00:00.000 2
我怎样才能做到这一点?
修改
dt datetime
列有重复的值(完全相同的日期!)
我正在使用SQL Server 2005
答案 0 :(得分:1)
您可以使用排名子选项来仅获取ID最高排名的条目:
select id, dt, seq
from (
select id, dt, seq, rank() over (partition by id order by dt desc, seq desc) as r
from #temp
) ranked
where r=1;
答案 1 :(得分:1)
SELECT ID, DT, SEQ
FROM (
SELECT ID, DT, SEQ, Row_Number()
OVER (PARTITION BY id ORDER BY dt DESC, seq DESC) AS row_number
FROM temp
) cte
WHERE row_number = 1;
答案 2 :(得分:0)
Select id, dt, seq
From #temp t
where dt = (Select Max(dt) from #temp
Where id = t.Id)
如果存在重复的行,则还需要指定查询处理器应使用哪些来确定要返回的重复项。假设您想要seq
的最低值,
然后你可以写:
Select id, dt, seq
From #temp t
where dt = (Select Max(dt) from #temp
Where id = t.Id)
and seq = (Select Min(Seq) from #temp
where id = t.Id
and dt = t.dt)
答案 3 :(得分:0)
通过试验和错误,我可能找到了解决方案,但我不完全确定这是正确的:
select A.id, B.dt, max(B.seq)
from (select id, max(dt) as maxDt
from #temp
group by id) as A
inner join #temp as B on A.id = B.id AND A.maxDt = B.dt
group by A.id, B.dt