How can I use the TSQL commands Top and IN together in SQL Server? [duplicate]

oxf4rvwz  于 2023-05-16  发布在  SQL Server
关注(0)|答案(2)|浏览(125)

This question already has answers here:

Get top 1 row of each group (19 answers)
Closed 8 days ago.

The sample code that I am referring to is as follows:

SELECT top(3) * FROM AcceptorRequests
WHERE Terminal IN ('70270191','70347395')
ORDER BY Id DESC

But it works for only one terminal number. I want to display three end records for each terminal.

uubf1zoe

uubf1zoe1#

;with cte
as
(
SELECT  *,row_number() over (partition by terminal order by id desc) as rownum  FROM AcceptorRequests 
WHERE Terminal IN ('70270191','70347395')
)
select * from cte where rownum<=3
ztyzrc3y

ztyzrc3y2#

You could use union all :

SELECT top(3) * 
FROM AcceptorRequests 
WHERE Terminal = '70270191'
UNION ALL
SELECT top(3) * 
FROM AcceptorRequests 
WHERE Terminal = '70347395'
order by Id desc

相关问题