sql - 在不使用 Pivot 的情况下将行转换为列
问题描述
我有一个数据集,但示例数据将如下所示:
Country Date Category X Y
IN 2011-11-22 B 1 0
BA 2010-11-23 B 11 0.2
IN 2011-11-22 A 1 0
BA 2011-11-23 A 1 1
IN 2011-07-28 A 1 0
想把它转换成:输出
Country Date B_X B_Y A_X A_Y
IN 2011-11-22 1 0 1 0
BA 2010-11-23 11 0.2 1 1
IN 2011-07-28 0 0 1 0
我已经尝试过使用案例,但它没有给我想要的输出,任何人都可以帮忙!
解决方案
我认为您只想按country
/聚合date
并使用条件聚合:
select country, date,
sum(case when category = 'B' then x end) as x_b,
sum(case when category = 'B' then y end) as y_b,
sum(case when category = 'A' then x end) as x_a,
sum(case when category = 'A' then y end) as y_a
from t
group by country, date;
推荐阅读
- ruby - 合并哈希数组中的重复值
- ruby - 如何查找 Google sheet API v4 的令牌
- postgresql - 可以为具有更多死元组的表的实时数据库运行真空完整详细命令吗?
- javascript - 根据 Knockout.js 中选择列表的选定选项显示或隐藏 HTML 元素?
- selenium - 直到在 Selenium 3 中被弃用
- python - 列表中字符串中间的正则表达式(Python)
- c# - 抛出异常的性能注意事项(重构此模式的最佳方法)
- php - 如何处理具有多种角色类型的同一用户
- python - Python:参考、字典和列表
- java - Java 应用程序使用 Datacap WTM 服务中止批次