使用数据透视SQL将列转换为行

时间:2018-09-03 15:45:41

标签: sql sqlite pivot

我有下表“ total_points”

printevery=

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

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

我的代码如下,并且我收到一个语法错误新的“ pivot”。知道我在哪里犯错了吗?

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

3 个答案:

答案 0 :(得分: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 :(得分:1)

您可以将case..when结构与聚合函数sum结合使用:

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

答案 2 :(得分: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
相关问题