SQL将一些列名转换为行值,将一个列名行值转换为列名
Posted
技术标签:
【中文标题】SQL将一些列名转换为行值,将一个列名行值转换为列名【英文标题】:SQL convert some column names to row values and one column name row values to column name 【发布时间】:2021-01-22 10:04:03 【问题描述】:我有一个按如下方式组织的表格:
Year |Account | Location| Measure1 |Measure2 |Measure3
2020 |123a |A |100 |20% |5
2020 |234b |B |75 |80% |8
2020 |122c |C |80 |78% |9
我想创建如下记录:
Year |Account | Measure |A |B |C
2020 |123a |Measure1 |100 | |
2020 |
2020 |234b |Measure2 | |80% |
2020 |122c |Measure3 | | |9
【问题讨论】:
为什么预期结果集中的所有 3 条记录都与帐户123a
关联?其他 2 个帐户怎么了?
解释第二行是如何出现的,只有一个年份的值。
【参考方案1】:
这个论坛不是为了解决你的编程任务。但是为了好玩:
select Year, Account, 'Measure1' as Measure, Measure1 as A, null as B, null as C
from my_table
where Location = 'A'
union
select Year, Account, 'Measure2' as Measure, Measure2 as A, null as B, null as C
from my_table
where Location = 'A'
...
union
select Year, Account, 'Measure1' as Measure, null as A, Measure1 as B, null as C
from my_table
where Location = 'B'
...
【讨论】:
【参考方案2】:我会推荐APPLY
:
select t.year, t.account, v.*
from t cross apply
(values ('Measure1', Measure1, null, null),
('Measure2', null, Measure2, null),
('Measure3', null, null, Measure3)
) v(measure, a, b, c);
这将返回除第二行之外的所有内容。目前尚不清楚您想要什么逻辑,但您可以添加:
union all
select distinct t.year, null, null, null, null, null
明确添加。
【讨论】:
以上是关于SQL将一些列名转换为行值,将一个列名行值转换为列名的主要内容,如果未能解决你的问题,请参考以下文章