在postgresql中透视等效

时间:2014-09-29 15:26:33

标签: sql postgresql

我在SQL Server中使用pivot

时有以下语句
Select YR, [1] As Beginning, [2] As Inter, [3] As Advanced, [4] As AdvHigh,Campus
From    
    (Select YR, Rating, StudentId, Campus 
        from mytable
        Where YR = '2014'
    ) As Data
    PIVOT   (Count(StudentId)
            For Rating IN ([1], [2], [3], [4])
    ) As Pvt

现在我正在尝试在Postgresql中编写相同的查询(我是postgresql的新手)。我查看了 tablefunc ,但我还不确定如何使用它。

任何帮助都会很棒!

1 个答案:

答案 0 :(得分:1)

我对postgresql中的tablefunc并不过分熟悉,但您可以使用带有聚合函数的PIVOT表达式来复制CASE

Select YR, 
  sum(case when ListeningProfRating = 1 then 1 else 0 end) As Begining,
  sum(case when ListeningProfRating = 2 then 1 else 0 end) As Inter,
  sum(case when ListeningProfRating = 3 then 1 else 0 end) As Advanced,
  sum(case when ListeningProfRating = 4 then 1 else 0 end) As AdvHigh
  Campus 
from mytable
Where YR = '2014' 
  AND ListeningScoreCode IN('S', 'B')
group by yr, campus