如何将列拆分为3列?

时间:2016-07-12 09:33:52

标签: sql sql-server tsql sql-server-2005

我已经有3个列的表1:

-------------------
|  A  |  B  |  C  |
-------------------

和表2:

----------------
|  id  |  col  |
----------------
|   1  |   2   |
|   2  |   6   |
|   3  |   1   |
|   4  |   8   |
|   5  |   9   |
|   6  |   5   |
|   7  |   4   |
|   8  |   3   |
|   9  |   7   |
----------------

我想从表2的col列插入表1,得到如下结果:

-------------------
|  A  |  B  |  C  |
-------------------
|  2  |  8  |  4  |
|  6  |  9  |  3  |
|  1  |  5  |  7  |
-------------------

有什么建议吗?非常感谢。

1 个答案:

答案 0 :(得分:4)

您可以尝试使用DENSE_RANK()确定每组3个,然后CASE EXPRESSION确定a/b/c

INSERT INTO Table1
SELECT MAX(CASE WHEN s.col % 3 = 1 THEN s.col END) as a,
       MAX(CASE WHEN s.col % 3 = 2 THEN s.col END) as b,
       MAX(CASE WHEN s.col % 3 = 0 THEN s.col END) as c
FROM (SELECT t.col ,
             DENSE_RANK() OVER(ORDER BY (s.col -1)/3) as group_rnk
      FROM Table2 s) s
GROUP BY s.group_rnk

我现在看到你标记了SQL-Server 2005,它还没有DENSE_RANK(),所以你可以用ROW_NUMBER()来试用它:

INSERT INTO Table1
SELECT MAX(CASE WHEN s.rnk % 3 = 1 THEN s.col END) as a,
       MAX(CASE WHEN s.rnk % 3 = 2 THEN s.col END) as b,
       MAX(CASE WHEN s.rnk % 3 = 0 THEN s.col END) as c
FROM (SELECT t.col ,
             ROW_NUMBER() OVER(ORDER BY t.id) as group_rnk
      FROM Table2 s) s
GROUP BY (s.group_rnk-1)/3