Postgresql CASE放在同一行

时间:2016-08-18 13:23:20

标签: sql database postgresql

我提出了一个对我的需求有用的查询:

select distinct min(term1_id), term2_id,
      case when distance = 0 then term2_id end as dist0,
      case when distance = 1 then term2_id end as dist1,
      case when distance = 2 then term2_id end as dist2,
      case when distance = 3 then term2_id end as dist3,
      case when distance = 4 then term2_id end as dist4,
      case when distance = 5 then term2_id end as dist5,
      case when distance = 6 then term2_id end as dist6,
      case when distance = 7 then term2_id end as dist7,
      case when distance = 8 then term2_id end as dist8,
      case when distance = 9 then term2_id end as dist9,
      case when distance = 10 then term2_id end as dist10,
      case when distance = 11 then term2_id end as dist11,
      case when distance = 12 then term2_id end as dist12,
      case when distance = 13 then term2_id end as dist13,
      case when distance = 14 then term2_id end as dist14,
      case when distance = 15 then term2_id end as dist15
 from graph_path
 group by term2_id, distance
 order by term2_id;

将结果返回“行”中,如下所示:

Term1_id dist0  dist1   dist2
1         1
1               5
1               118
1               12823
1               40006
1                        6
1                        7

如何将所有内容放在一行?

Term1_id  dist 0 dist1 dist2
    1       1      5     6
    1       118    7     etc...

有没有办法让它紧凑?而不是为每个dist创建一行?

1 个答案:

答案 0 :(得分:1)

使用聚合:

select term1_id, 
       max(case when distance = 0 then term2_id end) as dist0,
       max(case when distance = 1 then term2_id end) as dist1,
       max(case when distance = 2 then term2_id end) as dist2,
       max(case when distance = 3 then term2_id end) as dist3,
       max(case when distance = 4 then term2_id end) as dist4,
       max(case when distance = 5 then term2_id end) as dist5,
       max(case when distance = 6 then term2_id end) as dist6,
       max(case when distance = 7 then term2_id end) as dist7,
       max(case when distance = 8 then term2_id end) as dist8,
       max(case when distance = 9 then term2_id end) as dist9,
       max(case when distance = 10 then term2_id end) as dist10,
       max(case when distance = 11 then term2_id end) as dist11,
       max(case when distance = 12 then term2_id end) as dist12,
       max(case when distance = 13 then term2_id end) as dist13,
       max(case when distance = 14 then term2_id end) as dist14,
       max(case when distance = 15 then term2_id end) as dist15
 from graph_path
 group by term1_id
 order by term1_id;

根据查询中的逻辑,我认为您实际上想要按term1_id汇总。