2013-02-13 38 views
3

我有一個表A和3 columns-Postgres - 交叉表可能?

date  | type | value 
_________________________ 
2012-01-01 | 1 | 100 
2012-01-01 | 2 | 200 

2012-01-02 | 1 | 200 
2012-01-02 | 2 | 300 

2012-01-03 | 1 | 500 
2012-01-03 | 2 | 10 

是否有可能得到的結果的查詢,此數據的格式像這個 -

date  |  type-1  | type-2 
_____________________________________ 
2012-01-01  100    200 
2012-01-02  200    300 

它看起來像一個交叉表問題。但不知道。 任何想法如何寫一個SQL的呢?

+1

[This related answers](htt) p://stackoverflow.com/a/11751905/939860)可能對交叉表版本有所幫助。 – 2013-02-14 09:44:34

+0

[此博客條目](http://rowsandcolumns.blogspot.com/2011/10/postgresql-crosstab-query-rotate-table.html)可能會有用。 – Harpreet 2013-02-15 01:04:45

回答

4

可以使用聚合函數與CASE表達式得到的結果:

select date, 
    sum(case when type = 1 then value end) Type1, 
    sum(case when type = 2 then value end) Type2 
from yourtable 
group by date 

SQL Fiddle with Demo

您也可以加入你的桌子上多次:

select t1.date, 
    t1.value Type1, 
    t2.value Type2 
from yourtable t1 
left join yourtable t2 
    on t1.date = t2.date 
    and t2.type = 2 
where t1.type = 1 

SQL Fiddle with Demo

+0

優秀。我找到了使用交叉表的方法。類似於 - 從tableA中選擇* from crosstab('select date :: text,type :: text,value :: numeric(16,2),其中輸入(1,2)和日期''2012-02-06' 'and''2013-02-13''ORDER by 1,2' )AS ct(date text,type1 numeric(16,2),type2 numeric(16,2)),但比較解釋分析和您的查詢是方式太快。總是很好地學習更好的查詢:) – Harpreet 2013-02-13 22:49:36

+0

@Harpreet你的方式似乎比我的更加動態,但總是有不同的方式來查詢數據。你甚至可以在桌面上使用多個連接來做到這一點。 – Taryn 2013-02-13 23:27:17