用新列转置sql中的数据

问题描述 投票:3回答:3

我有一个类似的数据:

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

但是我面临2个问题

1。我无法转置化学和物理值

2。无法根据主题对数学,物理和化学进行分组

请帮助!

sql sql-server tsql pivot unpivot
3个回答
1
投票
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

Demo on DB Fiddle

col | col1 | col2 | col3:---- | ---: ---: ---:化学| 21 | 22 | 23数学| 50 | 60 | 80phy | 60 | 80 | 90


0
投票
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

0
投票
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
© www.soinside.com 2019 - 2024. All rights reserved.