将SQL中的数据转换为新列
我的数据如下:将SQL中的数据转换为新列,sql,sql-server,tsql,group-by,pivot,Sql,Sql Server,Tsql,Group By,Pivot,我的数据如下: id maths phy chem 1 50 60 21 2 60 80 22 3 80 90 23 现在我希望它看起来像: sub 1 2 3 math 50 60 80 phy 60 80 90 chem 21 22 23 我的代码: select * from mrks pivot ( max(maths) for id in ([1], [2], [3]) ) piv 然而,我面
id maths phy chem
1 50 60 21
2 60 80 22
3 80 90 23
现在我希望它看起来像:
sub 1 2 3
math 50 60 80
phy 60 80 90
chem 21 22 23
我的代码:
select *
from mrks
pivot
(
max(maths)
for id in ([1], [2], [3])
) piv
然而,我面临两个问题
在SQL Server中,您可以使用
交叉应用取消pivot,然后使用条件聚合进行透视:
select
col,
max(case when id = 1 then val end) col1,
max(case when id = 2 then val end) col2,
max(case when id = 3 then val end) col3
from mytable t
cross apply (values ('maths', maths), ('phy', phy), ('chem', chem)) p(col, val)
group by col
:
col | col1 | col2 | col3
:---- | ---: | ---: | ---:
chem | 21 | 22 | 23
maths | 50 | 60 | 80
phy | 60 | 80 | 90
col | col1 | col2 | col3
:---- | ---: | ---: | ---:
化学| 21 | 22 | 23
数学| 50 | 60 | 80
phy | 60 | 80 | 90
您不能在多个列上执行PIVOT
,您可以使用UNION
实现所需的输出,如下所示
SELECT 'Math' AS Sub,*
FROM (SELECT id ,maths FROM mrks) t
PIVOT(MAX(maths) FOR id IN ([1], [2], [3])) piv
UNION ALL
SELECT 'Phy' AS Sub,*
FROM (SELECT id,phy FROM mrks) t
PIVOT(MAX(phy) FOR id IN ([1], [2], [3])) piv
UNION ALL
SELECT 'Chem' AS Sub,*
FROM (SELECT id,chem FROM mrks) t
PIVOT(MAX(chem) FOR id IN ([1], [2], [3])) piv
这也会起作用
DECLARE @tble TABLE (id INT, maths INT, phy INT, chem INT)
INSERT INTO @tble VALUES
(1,50,60,21),(2,60,80,22),(3,80,90,23);
select * from(
SELECT ID,maths AS Scores, 'maths' as Subjects FROM @tble
UNION
SELECT ID,phy AS Scores, 'phy' as Subjects FROM @tble
UNION
SELECT ID,chem AS Scores, 'chem' as Subjects FROM @tble
) s
PIVOT
(
MIN(Scores)
FOR id IN ([1], [2], [3])
) piv
如果有人插入行(4、75、77、81),您预计会发生什么?