0
我正在使用Postgres 9.4。我有這樣一個表:Postgres:將具有不同列數的查詢連接到單個結果集中?
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]
,但它似乎暗示結果必須在相同的順序,我不能保證。我甚至不能保證列數相同,因爲並非所有組織都會在每個月花費在所有藥物上。
我是否需要製作一個新表,並在其上運行查詢?或者離線加入我的數據?