gpt4 book ai didi

sql - 使用新列转置 SQL 中的数据

转载 作者:行者123 更新时间:2023-12-04 13:30:28 25 4
gpt4 key购买 nike

我有这样的数据:

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

但是我面临两个问题

  1. 我无法调换化学和物理值

  2. 无法将数学、物理和化学归为主题

最佳答案

在 SQL Server 中,您可以使用交叉应用 取消透视,然后使用条件聚合进行透视:

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:---- | ---: | ---: | ---:chem  |   21 |   22 |   23maths |   50 |   60 |   80phy   |   60 |   80 |   90

关于sql - 使用新列转置 SQL 中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60276548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com