2

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

1
2
3
4
...
20

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

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

4 回答 4

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在这里

于 2013-06-09T20:00:33.403 回答
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
于 2013-06-10T05:31:27.267 回答
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
于 2013-06-09T19:57:22.370 回答
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 的数字。

于 2013-06-09T20:12:33.547 回答