2017-05-21 22 views
0

在Postgresql中,我的一列只包含5個值中的一個。這5個值中的一個是「成熟」。我正在嘗試編寫一個查詢,以計算整個表的特定切割次數「成熟」出現在該列中的次數。如何聚合pgsql表的列中唯一值的計數並在列中顯示它們?

以下查詢產生錯誤:syntax error at or near "Matured"

查詢:

select count(case when stagename is Matured end) from db_table 

另外,我有以下結果:

"Matured";694 
"Credit Approved";3 
"Delinquent";572 
"Current";1356 
"Canceled";16 

使用查詢:

select distinct stagename, 
     sum(case when stagename is not null then 1 else 0 end) 
     from db_table 
     group by stagename 

但我需要的是結果列不是行。像這樣:

  |Matured |Credit Approved |Delinquent |Current |Canceled 

stage_count | 694個| 3個| 572個| 1356 | 16

任何想法?

+0

'我試圖編寫一個查詢來計算「成熟」出現在該列中的次數 - 爲什麼不只是:'select table count'(*)where column ='Matured''? –

+0

爲什麼你需要它在列中,而不是行?首先想到的是'select stagename,從db_table group by stagename'中選擇count(*),然後使用類似python的方法來執行'Transpose()'。有可能在PSQL中做到這一點,但我不明白這一列的要求。 – Henry

+0

其實,我沒有想到用R來做轉置,試圖在一個查詢中得到所有的東西。謝謝! PS:我需要在一張桌子上,因爲我正在做一個大桌子的月份明智的分割。它需要與明月的其餘部分保持在同一張表格中,否則就會失去語境。 –

回答

0

您在查詢中錯過了單引號Matured以及語句不正確的情況,這就是爲什麼它返回語法錯誤的原因。您可以使用下面的查詢來獲得所需的結果。 您還可以閱讀關於postgres的crosstab函數。

select count(case when stagename = 'Matured' then 1 end), 
count(case when stagename = 'Credit Approved' then 1 end), 
count(case when stagename = 'Delinquent' then 1 end), 
count(case when stagename = 'Current' then 1 end), 
count(case when stagename = 'Canceled' then 1 end) 
from db_table 

注:如果列包含開頭和結尾的空間,然後使用微調功能與您的列名,然後進行比較。

相關問題