SQL 中的 PIVOT 问题

PIVOT issue in SQL

我无法解决 SQL 中我的数据透视函数的问题。我想保留 uid 列,但结果中每个 uid 只有一行 + sc_2015、sc_2016、sc_2017 等的列(在原始 table ,每年每个月有一个 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')
);

我建议放弃 PIVOT 运算符,而只在此处使用旧式枢轴查询:

SELECT
    t1.uid,
    AVG(CASE WHEN t2.score_year = 2015 THEN t2.score END) AS avg_score_2015,
    AVG(CASE WHEN t2.score_year = 2016 THEN t2.score END) AS avg_score_2016
    AVG(CASE WHEN t2.score_year = 2017 THEN t2.score END) AS avg_score_2017,
    AVG(CASE WHEN t2.score_year = 2018 THEN t2.score END) AS avg_score_2018
FROM table1 t1
LEFT JOIN table2 t2
    ON t1.uid = t2.uid
GROUP BY
    t1.uid;

我建议不使用 PIVOT 的原因是在许多情况下,上述版本实际上会执行得更好。恕我直言,代码更容易阅读和维护。

编辑:

一个可能写成 PIVOT 的版本应该是这样的:

SELECT uid, [2015], [2016], [2017], [2018]
FROM
(
    SELECT t1.uid, t2.score, t2.score_year
    FROM table1 t1
    LEFT JOIN table2 t2
        ON t1.uid = t2.uid
    WHERE t2.score_year BETWEEN 2015 AND 2018
) AS source
PIVOT
(
    AVG(score)
    FOR score_year IN ([2015], [2016], [2017], [2018])
) AS pivotal;