使用pivot SQL将列转换为行

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用pivot SQL将列转换为行相关的知识,希望对你有一定的参考价值。

我有下表'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;
答案

你需要删除'

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

另一答案

您可以使用具有聚合函数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

另一答案

进行这些更改

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

以上是关于使用pivot SQL将列转换为行的主要内容,如果未能解决你的问题,请参考以下文章

需要 PIVOT 或 CASE 解决方案来将列转换为行(如果可能,非动态)

SQL Server:将列转换为行

在没有任何聚合函数的情况下将列数据转换为行

SQL:在 Chartio 中动态地将列转换为行

oracle 10g如何将列转换为行

sql 将列数据转换为行