sql - 如何旋转表格的几列并获得所需格式的结果。?
问题描述
如何旋转下表以达到所需的结果。txtItem 值不是固定的,可以有 n 个 txtItem 值。
txtItem Rate Revenue Cost
A 1200 45 30
B 1300 55 40
C 1400 60 30
D 2100 55 35
预期结果:
ColumnName A B C D
Rate 1200 1300 1400 2100
Revenue 45 55 60 55
Cost 30 40 30 35
解决方案
这是unvpivot
& pivot
,所以你可以这样做:
select colname,
max(case when txtItem = 'A' then val end) as A,
max(case when txtItem = 'B' then val end) as B,
max(case when txtItem = 'C' then val end) as C,
max(case when txtItem = 'D' then val end) as D
from table t cross apply
( values (1, Rate, 'Rate'), (2, Revenue, 'Revenue'), (3, Cost, 'Cost')
) tt(seq, val, colname)
group by seq, colname
order by seq;
推荐阅读
- python - 计算pandas dataFrame中所有行的差之和
- angular - 如何修复错误“Type 'Observable
' 不可分配给类型 'EffectResult ’”? - symfony - Symfony/Doctrine:由管理员添加实体的属性
- vb.net - 如何使用应用程序配置文件中的数据库连接,而不必总是在表单中编码/输入连接字符串
- angular5 - Ag 网格分页箭头未正确显示
- python - cache_read 流错误:无法预填充缓冲区
- java - 尽管没有任何改变,但简单的应用程序崩溃
- java - Redis 消费者无法消费特定事件
- python - 如果 X 列包含字符串,则在 Y 列中查找子字符串的位置 - PYTHON
- python - tkinter filedialog 没有隐藏文件夹