你可以在SQL Server中如何同时使用TSQL命令Top和IN?

huangapple go评论69阅读模式
英文:

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

问题

以下是翻译好的内容:

示例代码如下:

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

但它只适用于一个终端号码。我想为每个终端显示三个最终记录。

英文:

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.

答案1

得分: 0

;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
英文:
;with cte
as
(
SELECT  *,row_number() over (partition by terminal order by id desc) as rownum  FROM AcceptorRequests 
WHERE Terminal IN (&#39;70270191&#39;,&#39;70347395&#39;)
)
select * from cte where rownum&lt;=3

答案2

得分: -1

你可以使用 union all

SELECT top(3) * 
FROM AcceptorRequests 
WHERE Terminal = '70270191'
UNION ALL
SELECT top(3) * 
FROM AcceptorRequests 
WHERE Terminal = '70347395'
ORDER BY Id DESC
英文:

You could use union all :

SELECT top(3) * 
FROM AcceptorRequests 
WHERE Terminal = &#39;70270191&#39;
UNION ALL
SELECT top(3) * 
FROM AcceptorRequests 
WHERE Terminal = &#39;70347395&#39;
order by Id desc

huangapple
  • 本文由 发表于 2023年5月7日 17:51:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76193180.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定