Sql 如何更改表格的布局/结构?

Sql 如何更改表格的布局/结构?,sql,database,oracle,Sql,Database,Oracle,我目前有一个表,其中有3列。列最好描述为组id、任务和任务计数。最多有15个可能的任务和超过500000个组ID。task_count是该任务的组id中发生的事件数。当前,该表如下所示: group_id task_count task 5555 45 A 5555 4 N 5624 67 A 5624 23 O 5624 42

我目前有一个表,其中有3列。列最好描述为组id、任务和任务计数。最多有15个可能的任务和超过500000个组ID。task_count是该任务的组id中发生的事件数。当前,该表如下所示:

group_id    task_count  task
5555        45          A
5555        4           N
5624        67          A
5624        23          O
5624        42          X
所以在5555组,我们只有两个任务: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;

谢谢,成功了!