我有一个包含以下列的表:Reportdate,Category。
Reportdate Category
-------------------
01/01/2013 IT
01/01/2013 Grounds
01/01/2013 HVAC
01/03/2013 HVAC
02/01/2013 IT
02/02/2013 IT
02/02/2013 HVAC
02/02/2013 Grounds
我需要一个输出以下内容的查询:
Jan Feb
---------------------------
IT 1 2
Grounds 1 1
HVAC 2 1
如果有人可以提供帮助,我会非常感激。感谢
答案 0 :(得分:1)
一种简单的方法是使用条件聚合:
select category,
sum(case when extract(month from reportdate) = 1 then 1 else 0 end) as Jan,
sum(case when extract(month from reportdate) = 2 then 1 else 0 end) as Feb
from table
group by category;
答案 1 :(得分:0)
您可以使用PIVOT
,也可以尝试以下方法:
SELECT category
, SUM(DECODE(EXTRACT(MONTH FROM reportdate), 1, 1, 0)) AS "Jan"
, SUM(DECODE(EXTRACT(MONTH FROM reportdate), 2, 1, 0)) AS "Feb"
, SUM(DECODE(EXTRACT(MONTH FROM reportdate), 3, 1, 0)) AS "Mar"
, SUM(DECODE(EXTRACT(MONTH FROM reportdate), 4, 1, 0)) AS "Apr"
, SUM(DECODE(EXTRACT(MONTH FROM reportdate), 5, 1, 0)) AS "May"
, SUM(DECODE(EXTRACT(MONTH FROM reportdate), 6, 1, 0)) AS "Jun"
, SUM(DECODE(EXTRACT(MONTH FROM reportdate), 7, 1, 0)) AS "Jul"
, SUM(DECODE(EXTRACT(MONTH FROM reportdate), 8, 1, 0)) AS "Aug"
, SUM(DECODE(EXTRACT(MONTH FROM reportdate), 9, 1, 0)) AS "Sep"
, SUM(DECODE(EXTRACT(MONTH FROM reportdate), 10, 1, 0)) AS "Oct"
, SUM(DECODE(EXTRACT(MONTH FROM reportdate), 11, 1, 0)) AS "Nov"
, SUM(DECODE(EXTRACT(MONTH FROM reportdate), 12, 1, 0)) AS "Dec"
FROM mytable
GROUP BY category
如果你想按年份区分可能会使事情变得复杂的事情!