首页 > 解决方案 > 如何更改表格的布局/结构?

问题描述

我目前有一个包含 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”。将其转换为上述格式的最佳方法是什么?谢谢你。

标签: sqldatabaseoracle

解决方案


您可以使用条件聚合:

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;

推荐阅读