我有下表'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;
编辑:
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;
您可以使用具有聚合函数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
进行这些更改
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