sql - 如何更改表格的布局/结构?
问题描述
我目前有一个包含 3 列的表。这些列最好描述为 group_id、task 和 task_count。最多有 15 个可能的任务和超过 500,000 个 group_id。task_count 是该任务在 group_id 中发生的事件数。目前,该表如下所示:
group_id task_count task
5555 45 A
5555 4 N
5624 67 A
5624 23 O
5624 42 X
所以在 5555 组中,我们只有 2 个任务:A 完成了 45 次,N 完成了 4 次。在 5624 中,我们有 3 个任务及其各自的计数。我想做的是根据组 ID 将这些值放在它显示的位置。所以它看起来像:
group_id TASK_A TASK_N TASK_O TASK_X
5555 45 4 0 0
5624 67 0 23 42
请注意,我想将任务值合并到列名中,而不是“task_count”。将其转换为上述格式的最佳方法是什么?谢谢你。
解决方案
您可以使用条件聚合:
select group_id,
sum(case when task = 'A' then task_count else 0 end) as a,
sum(case when task = 'N' then task_count else 0 end) as n,
sum(case when task = 'O' then task_count else 0 end) as o,
sum(case when task = 'X' then task_count else 0 end) as x
from t
group by group_id;
据推测,您的原始表是由一些未汇总的基表构建的。您可以将其直接应用于该表:
select group_id,
sum(case when task = 'A' then 1 else 0 end) as a,
sum(case when task = 'N' then 1 else 0 end) as n,
sum(case when task = 'O' then 1 else 0 end) as o,
sum(case when task = 'X' then 1 else 0 end) as x
from base
group by group_id;
推荐阅读
- sql - SQL - 如何根据我输入的顺序过滤条目?
- c# - AR Foundation - 在屏幕上放置 2 次触控的预制件
- javascript - 尝试在功能组件之间传递状态但出现“未定义”错误
- angular - 如何使用chartjs在一个水平堆叠的条形图中显示一段时间内的进度
- angular - Subject.next() 没有从可观察的内部触发
- c# - ReadAsync 停止代码执行,不抛出异常,Task 仍在运行
- flutter - TextField 的 Flutter Cursor 在 setState 后移动到 Position 0
- java - 测试失败:java.lang.IllegalStateException:无法加载 ApplicationContext
- python-3.x - 用 Pandas 数据框中这两个数字的总和替换 + 符号
- typescript - Threejs Raycaster 在稍微超出对象时击中对象