2016-12-17 111 views
1

請幫我如何解決必須出現在GROUP BY子句或聚合函數中使用

我newbi在Postgres數據庫

select 
    case 
     when daftar ='sd' then kouta 
    end as a, 
    case 
     when daftar = 'smp' then kouta 
    end as b, 
    case 
     when daftar = 'sma' then kouta 
    end as c 
from 
    ajaran 
GROUP BY 
    tahun 

和結果誤差

[Err] ERROR: column "ajaran.daftar" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: select case when daftar='sd' then kouta end as a,case when ...

我想在MySQL中查詢相同的查詢,並且沒有錯誤和成功分組 如何在pgsql中使用group by?

我想按tahun

this my table

+2

MySQL是不正確的,讓無差錯運行查詢,但MySQL是比PostgreSQL的那麼嚴格(和大多數其他數據庫系統,真的)。 – Dai

+0

你期望輸出什麼數據?你知道'GROUP BY'是什麼意思嗎?在這種情況下,「tahun」是什麼意思?它與「kouta」有什麼關係? – Dai

回答

0

想必,你想sum()max()爲:

select tahun, 
     max(case when daftar = 'sd' then kouta end) as a, 
     max(case when daftar = 'smp' then kouta end) as b, 
     max(case when daftar = 'sma' then kouta end) as c 
from ajaran 
group by tahun; 

我認爲錯誤是相當清楚的。 。 。 daftarkouta既不在group by中,也不在您的查詢中的聚合函數中。如果沒有進一步的指導,例如樣本數據和期望的結果,哪種彙總最合適不明確。

+0

謝謝,所以我應該添加像sum,max等聚合... – faza

+0

@faza。 。 。是的,這是主意。 –

0

分組時,您必須每組返回一個行,但是您的選擇不會將這些值合併到一行中。

提供集合,例如使用max()

select 
    tahun, 
    max(case when daftar ='sd' then kouta end) a, 
    max(case when daftar = 'smp' then kouta end) b, 
    max(case when daftar = 'sma' then kouta end) c 
from ajaran 
group by tahun 
相關問題