2017-08-17 41 views
1

我有如下表:Postgress SQL列表性別類型與在同一行中值

SELECT name, location_id, store_date, type, fact_count FROM table_test ORDER BY name, store_date;

 
    name | location_id | store_date | type | fact_count 
Paris |   466 | 2015-12-01 | 0 |  255 
Paris |   466 | 2015-12-01 | 1 |  256 
Berlin |   329 | 2015-12-01 | 1 |  248 
Berlin |   329 | 2015-12-01 | 0 |  244 
Prague |   201 | 2015-12-01 | 1 |  107 
Prague |   201 | 2015-12-01 | 0 |  102 

如何列出在同一行類型+值(我永遠只有2種) ?

 
    name | location_id | store_date | type_0 | fact_count_for_type_0 | type_1 | fact_count_for_type_1 
Paris |   466 | 2015-12-01 | 0 |  255    | 1 |  256 
Berlin |   329 | 2015-12-01 | 0 |  244    | 1 |  248 
Prague |   201 | 2015-12-01 | 0 |  102    | 1 |  107 

回答

1
SELECT 
    name, 
    location_id, 
    store_date, 
    sum(fact_count * (type = 0)::int) as fact_count_type_0, 
    sum(fact_count * (type = 1)::int) as fact_count_type_1 
FROM table_test 
group by 1,2,3 
ORDER BY name, store_date; 
+0

感謝您的例子。我可以建立在此基礎上。 :) – Jerry