【发布时间】:2020-01-31 20:56:51
【问题描述】:
我无法解决我在 SQL 中的数据透视函数的问题。我想保留 uid 列,但我的结果中每个 uid 只有一行 + sc_2015、sc_2016、sc_2017 等的列。(在原始表中,每年每个月有一个 uid 行 + 分数列。)
SELECT * FROM
(
SELECT DISTINCT
t1.uid,
t2.score_year AS yr,
--averaging scores across 12-months per year per uid:
CAST(AVG(t2.score) OVER (PARTITION BY t1.uid,t2.score_year) AS DECIMAL(4,3)) AS avg_annual_score
FROM
table1 t1
INNER JOIN table2 t2
ON t1.uid
=
t2.uid
WHERE t2.score_year IN (
'2015',
'2016',
'2017',
'2018',
'2019')
)
PIVOT (
MAX(avg_annual_score) sc FOR yr IN (
'2015',
'2016',
'2017',
'2018',
'2019')
);
【问题讨论】:
-
您使用的是哪个 dbms?
-
dbms 是 SQL Server。
标签: sql sql-server pivot in-clause