我想扩大一个长表,有两个列扩大。我已经找到了将长表转换为宽表的解决方案,但它们都采用一列并将其转换为n列。我想取两列,并将表转换为2n列。
我使用这个解决方案成功地扩大了基于一列的表,但我不确定如何扩大第二列。
下面是一个类似于链接解决方案的样本数据集:
Date Person Number1 Number2
2015-01-03 A 4 6
2015-01-04 A 2 5
2015-01-05 A 3 1
2015-01-03 B 5 3
2015-01-04 B 6 4
2015-01-05 B 7 6
我想加宽两列"Number1"one_answers";Number2"使输出为:
Date A1 B1 A2 B2
2015-01-03 4 5 6 3
2015-01-04 2 6 5 4
2015-01-05 3 7 1 6
那么,根据diceslak对拓宽一列的回答,解决方案将是:
select Date,
isNull([A], 0) as A1,
isNull([B], 0) as B1
from
( select Date, Person, Number1, Number2
from tbl ) AS SourceTable
PIVOT
( max(Number1) for Person in ( [A], [B]) ) AS PivotTable;
但是第二个呢?我试着在PIVOT
中添加第二行,但那不起作用。我想我可以把表分成两部分,并连接产生的宽表,但这似乎是一个坏主意,因为它会创建这样长的代码。
对于多列pivot,更容易使用case
表达式
select [Date],
A1 = max(case when Person = 'A' then Number1 end),
B1 = max(case when Person = 'B' then Number1 end),
A2 = max(case when Person = 'A' then Number2 end),
B2 = max(case when Person = 'B' then Number2 end)
from SourceTable
group by [Date]
对于2n
,您不需要pivot,一个简单的JOIN就可以了:
SELECT
a.Date,
a.Number1 as "A1",
b.Number1 as "B1",
a.Number2 as "A2",
b.Number2 as "B2"
FROM tbl a
INNER JOIN tbl b on b.Date=a.Date AND b.Person='B'
WHERE a.Person='A'
看到:DBFIDDLE