SQL根据行值多次选择每一行

时间:2016-08-04 11:08:03

标签: sql sql-server tsql

假设我有一张这种形式的表格:

ID   value
1    2
2    1
3    4

最有效选择每一行value次的方式是什么?

查询的所需输出是

ID
1
1
2
3
3
3
3

3 个答案:

答案 0 :(得分:2)

如果你有一个数字表,你可以这样做:

select t.id
from t join
     numbers n
     on n.n <= t.value;

有多种方法可以构建数字表。这是一种适用于大多数数据库的强力方式:

select t.id
from t join
     (select 1 as n union all select 2 union all select 3) n
     on n.n <= t.value;

答案 1 :(得分:1)

使用Numbers表..

select id from #test t
cross apply
(select N  from dbo.numbers where n<t.num) b

输出

id
1
1
2
3
3
3
3

答案 2 :(得分:1)

DECLARE @MAX int;
SET @MAX = (SELECT MAX(VALUE) from vTable);

WITH R AS (SELECT 1 N 
            UNION ALL 
            SELECT N + 1 FROM R WHERE N < @MAX),

      AllROWS AS (SELECT 
                    V.ID , 
                    V.Value, 
                    row_number() OVER (Partition BY v.id ORDER BY v.id) CNT
                   FROM vTable v
                    CROSS JOIN 
                R)
    SELECT ID FROM ALLROWS  WHERE CNT <= value                
option(maxrecursion 0)

我过于复杂以上,你只需要

DECLARE @MAX int;
SET @MAX = (SELECT MAX(VALUE) from vTable);

WITH R AS (SELECT 1 N 
            UNION ALL 
            SELECT N + 1 FROM R WHERE N < @MAX)
    SELECT vTable.ID FROM R CROSS JOIN vTable WHERE R.N <= vTable.value ORDER BY vTable.Id            
option(maxrecursion 0)