T-SQL:检索n次特定行数,其中n在“IN”子句中定义

时间:2014-08-04 12:39:29

标签: sql sql-server loops cursor

此查询如何生成20个结果而不是10?

SELECT TOP 10 colA, colB, colC
FROM table
WHERE id in (1, 2)
ORDER BY colA, colB

我想看到10个id等于1的结果,另外10个id等于2.我是否必须使用游标?

3 个答案:

答案 0 :(得分:2)

也许union all会帮助你

SELECT TOP 10 colA, colB, colC FROM table WHERE id = 1
union all
SELECT TOP 10 colA, colB, colC FROM table WHERE id = 2 
ORDER BY colA, colB

答案 1 :(得分:2)

这样您就不需要关心IN子句中有多少ID。

;WITH MyCTE AS
(
    SELECT colA, 
           colB, 
           colC,
           ROW_NUMBER() OVER(PARTITION BY id ORDER BY colA, colB) AS rn
    FROM   table 
    WHERE id in (1, 2) 
)
SELECT *
FROM   MyCTE 
WHERE  rn<= 10
ORDER BY colA, colB

答案 2 :(得分:1)

这不是答案(但它太大而不适合评论) @Giannis,这是带有示例数据的代码。我将10改为3以节省一些空间。

DECLARE @T TABLE (id INT, colA int, colB int)
INSERT INTO @T VALUES (1,10,20), (2, 30, 40), (1,14,23), (2, 32, 45), (1,16,28), (2, 35, 42), (1,11,27), (2, 34, 41), (1,19,23), (2, 32, 48), (1,17,26), (2, 37, 42)

;WITH MyCTE AS
(
    SELECT id, colA, 
           colB,
        ROW_NUMBER() OVER(PARTITION BY id ORDER BY colA, colB) AS rn
    FROM   @T
    WHERE id in (1, 2) 
)
SELECT *
FROM   MyCTE 
WHERE  rn<= id*3
ORDER BY colA, colB

以下是结果
id colA colB rn
1 10 20 1
1 11 27 2
1 14 23 3
2 30 40 1
2 32 45 2
2 32 48 3
2 34 41 4
2 35 42 5
2 37 42 6

请注意,当id = 2

时,id * 3给出rn&lt; = 6

如果您将WHERE修改为rn&lt; = 3,则会得到以下结果 id colA colB rn
1 10 20 1
1 11 27 2
1 14 23 3
2 30 40 1
2 32 45 2
2 32 48 3

这是OP要求的