您需要一个数据透视表:
在 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