sql - 如何将一列拆分为多列
问题描述
所以我的问题是运行一个查询并得到这样的结果
WEEKS PRODUCT SELL
Week-1 Product-A 34
Week-1 Product-B 40
Week-1 Product-C 38
Week-1 Product-D 20
Week-2 Product-A 27
Week-2 Product-B 25
Week-2 Product-C 22
Week-2 Product-D 39
Week-3 Product-A 33
Week-3 Product-B 19
Week-3 Product-C 43
Week-3 Product-D 36
Week-4 Product-A 21
Week-4 Product-B 26
Week-4 Product-C 33
Week-4 Product-D 39
Week-5 Product-A 43
Week-5 Product-B 30
Week-5 Product-C 40
Week-5 Product-D 24
Week-6 Product-A 42
Week-6 Product-B 25
Week-6 Product-C 44
Week-6 Product-D 22
Week-7 Product-A 47
Week-7 Product-B 39
Week-7 Product-C 27
Week-7 Product-D 17
Week-8 Product-A 39
Week-8 Product-B 39
Week-8 Product-C 44
Week-8 Product-D 44
Week-9 Product-A 44
Week-9 Product-B 21
Week-9 Product-C 31
Week-9 Product-D 26
Week-10 Product-A 42
Week-10 Product-B 31
Week-10 Product-C 20
Week-10 Product-D 25
Week-11 Product-A 24
Week-11 Product-B 35
Week-11 Product-C 28
Week-11 Product-D 28
Week-12 Product-A 30
Week-12 Product-B 27
Week-12 Product-C 43
Week-12 Product-D 24
但我想要这样的结果
Week-1 Product-A 34 Product-B 40 Product-C 38 Product-D 20
Week-2 Product-A 27 Product-B 25 Product-C 22 Product-D 39
Week-3 Product-A 33 Product-B 19 Product-C 43 Product-D 36
Week-4 Product-A 21 Product-B 26 Product-C 33 Product-D 39
Week-5 Product-A 43 Product-B 30 Product-C 40 Product-D 24
Week-6 Product-A 42 Product-B 25 Product-C 44 Product-D 22
Week-7 Product-A 47 Product-B 39 Product-C 27 Product-D 17
Week-8 Product-A 39 Product-B 39 Product-C 44 Product-D 44
Week-9 Product-A 44 Product-B 21 Product-C 31 Product-D 26
Week-10 Product-A 42 Product-B 31 Product-C 20 Product-D 25
Week-11 Product-A 24 Product-B 35 Product-C 28 Product-D 28
Week-12 Product-A 30 Product-B 27 Product-C 43 Product-D 24
我能得到这样的结果吗谢谢
解决方案
您可以使用条件聚合:
select weeks,
sum(case when product = 'Product-A' then sell end) as sell_a,
sum(case when product = 'Product-B' then sell end) as sell_b,
sum(case when product = 'Product-C' then sell end) as sell_c,
sum(case when product = 'Product-D' then sell end) as sell_d
from t
group by weeks
order by weeks;
推荐阅读
- java - 检查谓词泛型的类型
- javascript - 如何在javascript中从父类触发子实例的事件?
- pyspark - 如何更新pyspark中的列值?
- maven - Maven "also-make" 的行为
- python - 如何在 tkinter 的同一个变量中绑定一个又一个函数?
- dbt - 如何修复“无法解析”的 sqlfluff lint 错误
- android - Android 11(仅限)FragmentManager 崩溃 - FragmentManager 已被销毁
- sqlite - 使用 Jetbrains 的 Datagrip 时如何保存 sqlite 数据库
- javascript - Tone.js 完全停止所有播放声音
- javascript - 如何用子元素的高度更新一个元素的高度