SQL将单行拆分为固定列数

时间:2015-09-02 20:45:33

标签: sql

我们需要将单行拆分为固定数量的多列。以下是数据集的示例:

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

期望的输出:

Column A        Column B       Column C      Column D
1                  2              3              4
5                  6              7             NULL

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

SQL Server解决方案:

创建样本表:

create table mytable (col1 int)

insert into mytable values
(1),
(2),
(3),
(4),
(5),
(6),
(7);

使用ModuloRow_Number(),您可以轻松完成此操作:

模数查询:

SELECT 
    R1.col1 as columnA,
    R2.col1 as columnB,
    R3.col1 as columnC,
    R4.col1 as columnD
FROM 
    (
        SELECT ROW_NUMBER() OVER (ORDER BY col1 ASC) AS RowNum, col1 
        FROM mytable 
        WHERE 
            col1 % 4 = 1
    ) AS R1
    FULL OUTER JOIN (
        SELECT ROW_NUMBER() OVER (ORDER BY col1 ASC) AS RowNum, col1 
        FROM mytable 
        WHERE 
            col1 % 4 = 2
    ) AS R2
    ON R1.RowNum = R2.RowNum
    FULL OUTER JOIN (
        SELECT ROW_NUMBER() OVER (ORDER BY col1 ASC) AS RowNum, col1 
        FROM mytable 
        WHERE 
            col1 % 4 = 3
   ) AS R3
    ON R2.RowNum = R3.RowNum
    FULL OUTER JOIN (
        SELECT ROW_NUMBER() OVER (ORDER BY col1 ASC) AS RowNum, col1 
        FROM mytable 
        WHERE 
            col1 % 4 = 0
   ) AS R4
    ON R4.RowNum = R3.RowNum

<强>结果:

+---------+---------+---------+---------+
| columnA | columnB | columnC | columnD |
+---------+---------+---------+---------+
|       1 |       2 |       3 | 4       |
|       5 |       6 |       7 | (null)  |
+---------+---------+---------+---------+

SQL Fiddle Demo