2017-09-23 53 views
2

我有一個關於人們工作條件和鄰居信息的數據庫。添加總行數並轉換爲百分比

我要顯示的信息圖表中的百分比是這樣的:

Neighbourhood Total Employed Unemployed Inactive 
Total   100  50   25  25 
1    100  45   30  25 
2    100  55   20  25 

要做到這一點,那我迄今所取得的代碼是:

select neighbourhood, Count (*) as Total, 
    Count(Case when (condition = 1) then 'employed' end) as employed, 
    Count (case when (condition = 2) then 'unemployed' end) as unemployed, 
    Count (Case when (condition =3) then 'Inactive' end) as Inactive 

    from table 
    group by neighbourhood 
    order by neighbourhood 

輸出爲代碼是(absolut數字組成,他們不會導致百分比以上):

Neighbourhood Total Employed Unemployed Inactive 
    1    600  300  200  100 
    2    450  220  159  80 

所以,我必須打開絕對數字百分比並添加總行數(從區域中總結數值),但我所有的努力都是失敗的。我無法解決如何添加Total行,也不知道如何爲每個社區計算百分比總計

我剛剛兩週前開始學習SQL,因此對於給您帶來的不便深表歉意。我盡力保持它的簡單(在我的數據庫有15個街區,如果他們是用數字標記它的確定)

感謝

回答

1

您需要工會的加總的行

select 'All' as neighbourhood, Count (*) as Total, 
    Count(Case when (condition = 1) then 1 end) as employed, 
    Count (case when (condition = 2) then 1 end) as unemployed, 
    Count (Case when (condition =3) then 1 end) as Inactive 

    from table 

    UNION all 

    select neighbourhood, Count (*) as Total, 
    Count(Case when (condition = 1) then 1 end) as employed, 
    Count (case when (condition = 2) then 1 end) as unemployed, 
    Count (Case when (condition =3) then 1 end) as Inactive 

    from table 
    group by neighbourhood 
    order by neighbourhood 
+0

我有一個錯誤消息:sintax無效的整數「所有」 – MatiasSc

+0

當我運行上面的聯盟代碼,鄰居列顯示爲「未知」。對於下面的聯盟代碼,鄰域是整數(沒關係,引擎蓋用數字命名) – MatiasSc

+0

你不能在整列和字符串在同一列,所以你需要將鄰居轉換爲字符串 –

1

可以使用grouping sets加總列數:

select neighbourhood, Count(*) as Total, 
     sum((condition = 1)::int) as employed, 
     sum((condition = 2)::int) as unemployed, 
     sum((condition = 3)::int) as Inactive 
from table 
group by grouping sets ((neighbourhood),()) 
order by neighbourhood; 

如果你想平均值內的每一行,然後用avg()而不是sum()