2014-02-17 21 views
0

ProductSales表的示例。我們如何在交叉表中執行以下任務?

--Table 創建表productsales ( 國家VARCHAR(20), 推銷員VARCHAR(20), 量整數 )

--insert幾個記錄插入productsales 插入到productsales值( '英國', '薩姆',25000); ... ...

- 將在plpgsql中的「crosstab」中執行的查詢,而不是使用pivot操作符。 選擇推銷員,英國,美國,阿聯酋 從productsales 支點 - 我知道PLPGSQL爲國家 IN([英] [美] [阿聯酋]) 這是不行的 ( 總和(金額) ) AS pt

回答

1

要創建crosstab,您可以使用PostgreSQL附帶的tablefunc模塊。你需要先安裝它(這樣做,將取決於你如何安裝的PostgreSQL的方式),然後創建擴展:

CREATE EXTENSION tablefunc; 

有了到位,你可以簡單的做你的crosstab查詢:

SELECT * FROM crosstab($$ 
     /* Your normal query with your own filters (the fields must be always at the same order) */ 
     SELECT salesman, country, amount 
     FROM productsales 
     WHERE country IN ('UAE','UK','US') 
     /* The ORDER is really important here */ 
     ORDER BY 1, 2 
    $$, 
    /* The values that will be crossed, notice they are ordered alphabetically */ 
    $$VALUES('UAE'),('UK'),('US')$$ 
) AS 
/* Here you tell which columns and types you expect */ 
productsales(salesman varchar(20), uae integer, uk integer, us integer); 
+0

非常感謝您的協助。 –

相關問題