2011-10-26 21 views
3

我有這樣的查詢:顯示一列的多個值在一排的PostgreSQL

select to_date(to_char(registime, 'YYYY-MM'),'YYYY-MM') as dt,count(id) as total_call 
from all_info 
where alarm_id is null 
group by dt 
order by dt 

而結果就像這樣:

dt   total_call  
2011-03-01  45 
2011-04-01  61 
2011-05-01  62 
2011-06-01  41 
2011-07-01  48 
2011-08-01  42 
2011-09-01  28 
2011-10-01  39 

我想要的結果就像在演示下面,以表格的形式:

2011-03-01 2011-04-01 2011-05-01 2011-06-01 .......... 
    45   61   62   41 

我想用交叉,但它似乎沒有 上班?

+0

對不起,但你怎麼試圖顯示的數據,你使用什麼語言/程序? –

+0

感謝丹尼爾,我只是使用結果作爲數據源,在這種情況下,我可以在ireprot中顯示結果。 Ireport是一名報告設計師。 – diligent

+1

這是任何幫助:http://www.postgresonline.com/journal/archives/14-CrossTab-Queries-in-PostgreSQL-using-tablefunc-contrib.html –

回答

3

查看contrib模塊tablefunc。它提供了您正在尋找的那種數據透視表功能。 查看manual here

請按照installation instructions here或在上面的評論中建議的文章@Paul Tomblin。

然後你的函數看起來是這樣的:

SELECT * 
    FROM crosstab($$ 
SELECT 'total_calls'::text AS col_name 
     ,to_char(registime, '"x"YYYY_MM_01') as dt 
     ,count(id) as total_call 
FROM all_info 
WHERE alarm_id is null 
GROUP BY dt 
ORDER BY dt 
$$) 
AS ct(
call_day text 
,x2011_03_01 int8 
,x2011_04_01 int8 
,x2011_05_01 int8 
,x2011_06_01 int8 
,x2011_07_01 int8 
,x2011_08_01 int8 
,x2011_09_01 int8 
,x2011_10_01 int8); 

輸出:

call_day | x2011_03_01 | x2011_04_01 | x2011_05_01 | x2011_06_01 | x2011_07_01 | x2011_08_01 | x2011_09_01 | x2011_10_01 
-------------+-------------+-------------+-------------+-------------+-------------+-------------+-------------+------------- 
total_calls |   1 |   4 |   4 |   2 |   1 |   5 |   1 |   1 

列名不能以數字開頭(或者你有雙引號),這就是爲什麼我帶x的日期前綴。我也簡化了你的查詢。
您可以將其封裝在視圖或函數中以便重複使用。
也許是一個動態調整列名和EXECUTE的plpgsql函數。

More details, explanation and links in this related answer

+0

謝謝你,非常好。我怎麼能接受你的答案?我找不到它。 – diligent

+0

在您接受答案之前,問題出現15分鐘的時間限制。有關詳情,請參閱此處:http://meta.stackexchange.com/questions/38090/discourage-questions-being-marked-as-answered-within-an-hour-or-so-of-being-post/44099# 44099。在這裏:http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work。現在,如果刷新頁面,您應該看到答案旁邊的複選標記。 –

相關問題