在PostgreSQL中实现Crosstab查询通常有两种方法:使用crosstab函数和手动实现crosstab查询。
CREATE EXTENSION tablefunc;
SELECT * FROM crosstab(
'SELECT category, year, amount FROM sales',
'SELECT DISTINCT year FROM sales ORDER BY 1'
) AS ct (category text, "2019" numeric, "2020" numeric, "2021" numeric);
SELECT category,
SUM(CASE WHEN year = '2019' THEN amount ELSE 0 END) AS "2019",
SUM(CASE WHEN year = '2020' THEN amount ELSE 0 END) AS "2020",
SUM(CASE WHEN year = '2021' THEN amount ELSE 0 END) AS "2021"
FROM sales
GROUP BY category;
这两种方法都可以实现Crosstab查询,选择哪种方法取决于个人偏好和实际情况。