2016-02-13 49 views
0

我有一張包含加油站價格的表格。每個加油站有不同燃料類型(柴油,普通,超級)和服務類型(汽車服務,全面服務)的六個價格記錄。例如我對加油站的價格的記錄與「id_gas_station」表「gas_station_prices」 = 155創建一個視圖,在每一行中包含來自六個不同記錄的數據[PostgresSQL]

id_price|price_gas_station|id_gas_station|id_fuel_type|id_service_type 
3041 |2.29    |155   |2   |1 
2631 |2.52    |155   |1   |1 
3861 |2.43    |155   |1   |2  
4681 |1.84    |155   |3   |2  
3451 |1.93    |155   |3   |1  
4271 |2.2    |155   |2   |2  

我有兩個目錄,它包含燃料類型和服務類型

fuel_type目錄:

id_fuel_type |name_fuel_type 
1   |SUPER 
2   |REGULAR 
3   |DIESEL 

的service_type目錄:

id_service_type |name_service_type 
1    |FULL SERVICE 
2    |AUTO SERVICE 

我需要按照以下步驟創建包含列「price_gas_station」六個創紀錄的價格在單行工會爲每gas_station一個SQL視圖:

id_gas_station|fs_sup_p |fs_reg_p |fs_die_p |as_sup_p |as_reg_p|as_die_p| 
155   |2.52  |2.29  |1.93  |2.43  |2.2  |1.84 

回答

0

可以使用有條件的聚集它:

SELECT id_gas_station, 
     MAX(CASE WHEN id_fuel_type = 1 AND 
        id_service_type = 1 
       THEN price_gas_station 
      END) AS fs_sup_p, 
     MAX(CASE WHEN id_fuel_type = 2 AND 
        id_service_type = 1 
       THEN price_gas_station 
      END) AS fs_reg_p, 
     MAX(CASE WHEN id_fuel_type = 3 AND 
        id_service_type = 1 
       THEN price_gas_station 
      END) AS fs_die_p, 
     ... etc 
FROM mytable 
GROUP BY id_gas_station 
+0

非常感謝您的解決方案完美工作! –

0

下面是一個使用CROSSTAB(http://www.postgresql.org/docs/current/static/tablefunc.html

SELECT * 
FROM crosstab(
' 
SELECT 
    gsp.id_gas_station, 
    LOWER(LEFT(st.name_service_type,4) || ft.name_fuel_type) AS price_type, 
    gsp.price_gas_station 
FROM 
    gas_station_prices gsp 
JOIN 
    fuel_type ft 
    ON (ft.id_fuel_type = gsp.id_fuel_type) 
JOIN 
    service_type st 
    ON (st.id_service_type = gsp.id_service_type) 
ORDER BY 
    1,2 
' 
) AS ct (
id_gas_station INT, 
auto_diesel FLOAT, 
auto_regular FLOAT, 
auto_super FLOAT, 
full_diesel FLOAT, 
full_regular FLOAT, 
full_super FLOAT 
); 

Giorgos溶液應的另一種方式一樣好 - 也許更具可讀性?這是大多數人的偏好問題。我只是想告訴你一個選擇。

+0

謝謝Nicarus你的解決方案也工作過! –

相關問題