在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查詢,選擇哪種方法取決于個人偏好和實際情況。