2017-02-03 30 views

回答

1

交叉表()的查詢看起來像這樣:

SELECT col1 
    , col2 AS "X" 
    , col3 AS "Y" 
FROM crosstab(
     'SELECT col1 , col2, col3 
     FROM table 
     ORDER BY 1' 
     ,$$VALUES ('X'::text), ('Y')$$ 
) AS ct (
    col1 int 
, col2 numeric -- use actual data type! 
, col3 numeric); 

解釋和鏈接在這個有關的答案: PostgreSQL Crosstab Query

+0

這種看起來像我想要的。然而,看起來'X'和'Y'需要被硬編碼,這是我不太確定的。我會解決它。 –

0

一種方法是有條件的聚合:對於你的例子

select col1, 
     max(case when col2 = 'X' then col3 end) as x, 
     max(case when col2 = 'Y' then col3 end) as y 
from t 
group by col1; 
相關問題