Postgres:将具有不同列数的查询连接到一个结果集中?

时间:2015-06-26 14:57:16

标签: postgresql

我使用的是Postgres 9.4。我有一张这样的桌子:

 org_id            | character varying(3)    | not null
 drug_code         | character varying(15)   | not null
 actual_cost       | double precision        | not null
 processing_date   | date                    | not null

我想运行这样的查询:

 SELECT org_id, SUM(actual_cost) AS cost_123 FROM mytable
 WHERE drug_code='123'
 AND processing_date < '2014-03-01' 
 AND processing_date > '2014-01-10'
 GROUP BY org_id

产生:

   org_id    cost_123   
   1         200.12    
   2         400.15     

还有另一个问题:

 SELECT org_id, SUM(actual_cost) AS cost_234 FROM mytable
 WHERE drug_code='234'
 AND processing_date < '2014-03-01' 
 AND processing_date > '2014-01-10'
 GROUP BY org_id

产生:

   org_id    cost_123   
   2         68.98    
   3         66.54

得到一组这样的结果:

org_id    cost_123   cost_234
1         200.12     NULL 
2         400.15     68.98
3         NULL       66.54

Postgres有可能吗?

我一直在关注[UNION][1],但似乎暗示结果必须按照相同的顺序排列,我无法保证。我甚至无法保证会有相同数量的专栏,因为并非所有组织都会在每个月都花在所有药物上。

我是否需要创建一个新表,并对其运行查询?或者离线加入我的数据?

1 个答案:

答案 0 :(得分:2)

一种方法是条件聚合:

SELECT org_id,
        SUM(CASE WHEN drug_code = '123' THEN actual_cost ELSE 0 END) AS cost_123,
        SUM(CASE WHEN drug_code = '234' THEN actual_cost ELSE 0 END) AS cost_234 FROM mytable
 WHERE drug_code in ('123', '234') AND
       processing_date < '2014-03-01' AND
       processing_date > '2014-01-10'
 GROUP BY org_id;