SQL - 在SELECT CASE语句之后合并行

时间:2016-02-20 16:33:35

标签: sql postgresql

我想整合具有从SELECT CASE语句返回的匹配ID的行。我在pgAdmin 3数据库上使用PG-9.3.4

这就是我对pgAdmin的看法: query result

这就是我想得到的:expected result

我已尝试将其分组,或将结果加入表格本身,但不行。有什么想法吗?

我的查询代码:

SELECT
    CASE
    WHEN t1.material LIKE '%Refuse%'
        THEN t1.disposal
    ELSE NULL
END AS msw_disp,

    CASE
    WHEN t1.material LIKE '%Met%'
        THEN t1.disposal
    ELSE NULL
END AS mgp_disp,

    CASE
    WHEN t1.material LIKE '%Paper%'
        THEN t1.disposal
    ELSE NULL
END AS pap_disp, t1.district

FROM dsny_net t1

2 个答案:

答案 0 :(得分:0)

AggregateGroup by添加到当前查询中应该完成工作

SELECT Max(CASE 
             WHEN t1.material LIKE '%Refuse%' THEN t1.disposal 
           END) AS msw_disp, 
       Max(CASE 
             WHEN t1.material LIKE '%Met%' THEN t1.disposal 
           END) AS mgp_disp, 
       Max(CASE 
             WHEN t1.material LIKE '%Paper%' THEN t1.disposal 
           END) AS pap_disp, 
       t1.district 
FROM   dsny_net t1 
GROUP  BY t1.district 

答案 1 :(得分:0)

同样的选择:

select
  district,
  unnest(array_agg(disposal) filter (where material like '%Refuse%')) as msw_disp,
  unnest(array_agg(disposal) filter (where material like '%Met%')) as mgp_disp,
  unnest(array_agg(disposal) filter (where material like '%Paper%')) as pap_disp,
from dsny_net
group by district;

使用max将删除除最大值

以外的所有其他值(如果有)

unnest(array_agg(disposal) filter (where material like ...)) as ...可以替换为max(disposal) filter (where material like ...) as..,以缩短查询次数。