我正在寻找一个简单的查询,以获得每组中最新发票日期的2行结果。虽然这个任务可以通过row_number()
完成,您可以在下面的代码中看到,我需要一个替代方案,只需要最小的复杂性。
代码:
create table #tt
(
id int,
invoiceDT datetime
)
insert into #tt
values(1,'01-01-2016 00:12'),(1,'01-02-2016 06:16'),(1,'01-01-2016 00:16')
,(2,'01-01-2016 01:12'),(2,'04-02-2016 06:16'),(2,'01-06-2016 00:16')
select *
from (
SELECT id,invoiceDT,row_number() over(partition by id order by invoiceDT desc) as rownum
FROM #tt
)tmp
where rownum <=2
我需要上面查询返回的相同结果
请提出替代方案。
答案 0 :(得分:1)
奇怪的请求,但是你去了:
WITH CTE as
(
SELECT distinct id FROM #tt t1
)
SELECT x.*
FROM CTE
CROSS APPLY
(
SELECT top 2 *
FROM #tt
WHERE CTE.id = id
ORDER BY invoiceDT desc
) x