我有一个返回表的视图:
cat_name | Jan | Feb | Mar | ... | YEAR
student | 0 | 23 | 12 | ... | 2013
student | 10 | 2 | 8 | ... | 1999
professor| 12 | 9 | 3 | ... | 2015
teacher | 3 | 8 | 5 | ... | 2015
我需要制作像这样返回smth的视图:
cat_name | 1999 | 2013 | 2015 | ...
student | 20 | 35 | 0 | ...
professor| 0 | 0 | 24 | ...
teacher | 0 | 0 | 16 | ...
汇总行并选择不同的cat_name:
SELECT cat_name, "YEAR",
COALESCE("Jan",0)+COALESCE("Feb",0)+COALESCE("Mar",0)+
... +COALESCE("Dec",0) AS sum
FROM view
GROUP BY "YEAR", cat_name, sum;
有没有办法让#34;年"值列名?年数不固定,也是cat_name的数量。
例如,如何使用(select distinct "YEAR" from view
)中的年份制作一些列表,并使用今年而不是2013年,2014年...... CASE WHEN "YEAR" = 2014
?
答案 0 :(得分:0)
您可以使用条件聚合执行此操作:
SELECT cat_name, "YEAR",
SUM(CASE WHEN "YEAR" = 2013
THEN COALESCE("Jan", 0) + COALESCE("Feb", 0) + COALESCE("Mar", 0)+ . . .
END) as "2013",
SUM(CASE WHEN "YEAR" = 2014
THEN COALESCE("Jan", 0) + COALESCE("Feb", 0) + COALESCE("Mar", 0)+ . . .
END) as "2014",
. . .
FROM view
GROUP BY cat_name;
如果输出中需要可变数量的列,则可以使用crosstab
查询。 Here就是一个例子。