使用pivot SQL将列转换为行

问题描述 投票:2回答:3

我有下表'total_points'

YEAR | COUNTRY | POINTS
----------------------
2014 | UK      | 100
2014 | ITALY   | 200
2015 | UK      | 100
2015 | ITALY   | 100
2016 | UK      | 300
2016 | ITALY   | 300

我正在尝试使用数据透视表转换为以下内容

YEAR | UK | ITALY
----------------
2014 | 100 | 200 
2015 | 100 | 100
2016 | 300 | 300

我的代码如下,我得到一个新的'pivot'语法错误。知道我在哪里弄错了吗?

CREATE VIEW total_club_points_pivoted AS
select * 
from 
(
    select YEAR, COUNTRY, POINTS
    from total_points
) src
pivot
(
    POINTS
    for COUNTRY in (['UK'], ['ITALY'])
) piv;
sql sqlite pivot
3个回答
1
投票

你需要删除'

select * 
from 
(
    select YEAR, COUNTRY, POINTS
    from total_points
) src
pivot
(
    MAX(POINTS) for COUNTRY in ([UK], [ITALY])  -- here removed ' + added agg func
) piv;

DBFiddle Demo


编辑:

SQLite等价物:

SELECT year,
     MAX(CASE WHEN Country='UK' THEN Points END) AS "UK",
     MAX(CASE WHEN Country='ITALY' THEN Points END) AS "Italy"
FROM total_points
GROUP BY year;

DBFiddle Demo2


1
投票

您可以使用具有聚合函数case..whensum结构:

CREATE VIEW total_club_points_pivoted AS
select YEAR, 
      sum(case when country = 'UK' then
         points
       end) as "UK",
      sum(case when country = 'ITALY' then
         points
       end) as "ITALY"       
  from total_points
 group by YEAR 
 order by YEAR;

 YEAR   UK  ITALY
 2014   100  200
 2015   100  100
 2016   300  300

SQL Fiddle Demo


0
投票

进行这些更改

CREATE VIEW total_club_points_pivoted AS
select * 
from 
(
    select YEAR, COUNTRY, POINTS
    from total_points
) src
pivot
(
    Sum(POINTS)
    for COUNTRY in (UK, ITALY)
) piv
© www.soinside.com 2019 - 2024. All rights reserved.