SQL |根据条件将列视为多列

时间:2018-01-18 23:49:07

标签: sql postgresql

Newbie Postgresql(9.6.6)问题:)

我想创建一个视图,根据不同的条件将单个列拆分为多个列。

示例表

  Name    Score   Season  
 ------- ------- -------- 
  John       12   Fall    
  John       15   Winter  
  John       13   Spring  
  Sally      17   Fall    
  Sally      10   Winter  
  Sally      14   Spring  
  Henry      16   Fall    
  Henry      12   Winter  
  Henry      18   Spring  

我希望View能够显示如下内容:

  Name    Fall Score   Winter Score   Spring Score  
 ------- ------------ -------------- -------------- 
  John            12             15             13  
  Sally           17             10             14  
  Henry           16             12             18  

“Score”字段分为几个不同的列,每个列都基于引用“Season”字段的WHERE子句填充。我已经查看了Window Functions和CASE Statements来实现这个目的,但到目前为止还没有成功。

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:5)

loadComponent上进行分组,然后在Name列上有条件地SUM进行分组时,从整个表中进行选择将有效:

Score

您是否使用SELECT "Name", SUM(CASE WHEN "Season" = 'Fall' THEN "Score" ELSE 0 END) AS "Fall", SUM(CASE WHEN "Season" = 'Winter' THEN "Score" ELSE 0 END) AS "Winter", SUM(CASE WHEN "Season" = 'Spring' THEN "Score" ELSE 0 END) AS "Spring" FROM "mytable" GROUP BY "Name" 取决于您以及数据的外观。如果每个(SUM()Name)对有一行,那么Season将与SUM()

同等地工作

答案 1 :(得分:1)

您需要一个数据透视表:

在SQL服务器上,您可以执行类似此示例的操作(希望它对于postgress是相同的),在其他版本的SQL中存在pivot关系运算符,但我不确定Pivot是否有效在Postgres

示例:

CREATE TABLE #Table
(
   Name nvarchar(400),
   Score int,
   Season nvarchar(400)
)

insert into #Table values ( 'John ',12,'Fall')
insert into #Table values ( 'John ',15,'Winter'   )
insert into #Table values ( 'John ',13,'Spring'   )
insert into #Table values ( 'Sally',17,'Fall   '  )
insert into #Table values ( 'Sally',10,'Winter'   )
insert into #Table values ( 'Sally',14,'Spring'   )
insert into #Table values ( 'Henry',16,'Fall'    ) 
insert into #Table values ( 'Henry',12,'Winter'   )
insert into #Table values ( 'Henry',18,'Spring'  )

select 
    c.Name
    ,sum(c.[Fall Score]) as [Fall Score]
    ,sum(c.[Winter Score]) as [Winter Score]
    ,sum(c.[Spring Score]) as [Spring Score]
from
(SELECT 
    t.name,
    case 
        when t.Season = 'Fall' then t.Score
        when t.Season = 'Winter' then 0
        when t.Season = 'Spring' then 0
    end as [Fall Score],
    case 
        when t.Season = 'Fall' then 0
        when t.Season = 'Winter' then t.Score
        when t.Season = 'Spring' then 0
    end as [Winter Score],
    case 
        when t.Season = 'Fall' then 0
        when t.Season = 'Winter' then 0
        when t.Season = 'Spring' then t.Score
    end as [Spring Score]
from #Table t
)as c 
group by c.name

enter image description here