将数据透视表分成多列和多行

时间:2017-11-08 15:55:57

标签: sql sql-server

背景 我有一个表,其中包含一个逗号分隔字符串的varchar(有多行类似于this问题。不幸的是我无法找到一种方法将csv varchar更改为临时表只是如此我正在考虑将自己分开。(我也很感激任何解决这个问题的答案,虽然它可能是一个单独的问题?)。

问题

我已成功拆分了字符串,现在正在生成类似于:

的输出
   -------------------------------------
   | Row Index  | Column Index | Value |
   -------------------------------------
   |     0      |      0       | (0,0) |
   |     0      |      1       | (1,0) |
   |     0      |      2       | (2,0) |
   |     1      |      0       | (0,1) |
   |     1      |      1       | (1,1) |
   |     1      |      2       | (2,1) |
   |     2      |      0       | (0,2) |
   |     2      |      1       | (1,2) |
   |     2      |      2       | (2,2) |
   -------------------------------------

我想将其转换为可以将其插入临时表中,最终结果如下:

   -------------------------------------
   | Column 1  | Column 2  | Column 3  |
   -------------------------------------
   |   (0,0)   |   (1,0)   |   (2,0)   |
   |   (0,1)   |   (1,1)   |   (2,1)   |
   |   (0,2)   |   (1,2)   |   (2,2)   |
   -------------------------------------

旁白

  1. 提前知道列数,但也欢迎不依赖于此的答案。
  2. 我知道我可以反复地将第一个表连接到外部连接以获得此结果但是这需要每列一次外连接(因为我有~9列这将是很多重复)并且我假设还有另一个方式。
  3. 性能不是关键,但最终表中将有大约2000行,8列。

2 个答案:

答案 0 :(得分:1)

使用条件聚合:

-----END PUBLIC KEY-----

rextester演示:http://rextester.com/QLPHR39222

返回:

select 
    RowIndex
  , Column1 = max(case when ColumnIndex=0 then Value end)
  , Column2 = max(case when ColumnIndex=1 then Value end)
  , Column3 = max(case when ColumnIndex=2 then Value end)
from t
group by RowIndex

+----------+---------+---------+---------+ | RowIndex | Column1 | Column2 | Column3 | +----------+---------+---------+---------+ | 0 | (0,0) | (1,0) | (2,0) | | 1 | (0,1) | (1,1) | (2,1) | | 2 | (0,2) | (1,2) | (2,2) | +----------+---------+---------+---------+

pivot()

答案 1 :(得分:1)

这是PIVOT查询(See The Docs)的简单应用:

select x.[0] Column1
     , x.[1] Column2
     , x.[2] Column3
  from YourData
 pivot (max(Value)
   for [Column Index]
    in ([0], [1], [2]) ) x
 order by x.[Row Index]

返回:

| Column1 | Column2 | Column3 |
|---------|---------|---------|
|   (0,0) |   (1,0) |   (2,0) |
|   (0,1) |   (1,1) |   (2,1) |
|   (0,2) |   (1,2) |   (2,2) |

SQL Fiddle

要添加更多列,只需向FOR column IN (list)部分添加更多列索引,并将相同的值添加到投影(选择列表)

相关问题