将整数序列转换为表格

时间:2013-06-09 19:27:59

标签: sql-server tsql

一个表只包含一个包含整数序列的列:

1
2
3
4
...
20

是否可以将其转换为包含三列且只有一个查询的表? 所以结果应该是:

1 2 3
4 5 6
7 8 9
...
19 20 null

4 个答案:

答案 0 :(得分:4)

尝试:

with cte as
(select myCol,
        floor((row_number() over (order by myCol)-1)/3) rn,
        (row_number() over (order by myCol)-1) % 3 + 1 cn
 from myTable)
select [1],[2],[3]
from
(select * from cte) as src
 pivot
(max(myCol) 
 for cn in ([1],[2],[3])) as pvt

SQLFiddle here

答案 1 :(得分:1)

试试这个 -

DECLARE @temp TABLE (id INT)
INSERT INTO @temp (id)
VALUES 
    (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),
    (11),(12),(13),(14),(15),(16),(17),(18),(19),(20)

SELECT [1], [2], [3]
FROM (
    SELECT 
          id
        , rn = (ROW_NUMBER() OVER (ORDER BY id) - 1) % 3 + 1
        , rn2 = (ROW_NUMBER() OVER (ORDER BY id) - 1) / 3
    FROM @temp
) t
PIVOT
(
    MAX(id)
    FOR rn IN ([1], [2], [3])
) pvt

答案 2 :(得分:0)

这是一个解决方案:

declare @t table (n int)
insert into @t values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13)

select n0, n1, n2

from (
    select n0, r from (
        select n [n0], row_number() over (order by n) - 1 [r]
        from @t 
    ) t0
) tt0

left join (
    select n1, r
    from (
        select n [n1], row_number() over (order by n) - 1 [r]
        from @t 
    ) t1
    where t1.r % 3 = 1
) tt1 on (tt1.r / 3) = tt0.r / 3

left join (
    select n2, r
    from (
        select n [n2], row_number() over (order by n) - 1 [r]
        from @t 
    ) t2
    where t2.r % 3 = 2
) tt2 on (tt2.r / 3) = tt0.r / 3


where tt0.r % 3 = 0

答案 3 :(得分:0)

如果按顺序表示值只是递增1,那么你基本上可以用算术来做:

select mycol,
       (case when mycol + 1 <= maxval then mycol + 1 end),
       (case when mycol + 2 <= maxval then mycol + 2 end)
from myTable cross join
     (select min(myCol)%3 as offset,
             max(myCol) as maxval
      from myTable
     ) const
where (mycol - offset)%3 = 0;

其他解决方案更为通用 - 它们将在序列中转动任何值。这仅限于增加1的数字。