SQL结果按月分组

时间:2010-11-09 20:40:14

标签: sql oracle group-by

我试图在一个滚动的12个月期间返回一些结果,例如:

MONTH       IN   OUT
January    210    191
February   200    111
March      132    141
April      112    141
May        191    188 
etc...

如何在日期范围内展开结果,使用月份名称填充第一列?

在MSSQL中它会是这样的:

SELECT  COUNT(problem.problem_type = 'IN') AS IN, 
    COUNT(problem.problem_type = 'OUT') AS OUT, 
    DATEPART(year, DateTime) as Year,
    DATEPART(month, DateTime) as Month
FROM problem
WHERE   (DateTime >= dbo.FormatDateTime('2010-01-01')) 
    AND 
    (DateTime < dbo.FormatDateTime('2010-01-31'))
GROUP BY DATEPART(year, DateTime),
    DATEPART(month, DateTime);

但这是针对Oracle数据库的,因此DATEPART和DateTime不可用。

我的问题表大致是:

problem_ID Problem_type   IN_Date                     OUT_Date
   1           IN        2010-01-23 16:34:29.0       2010-02-29 13:06:28.0
   2           IN        2010-01-27 12:34:29.0       2010-01-29 12:01:28.0
   3           OUT       2010-02-13 13:24:29.0       2010-09-29 15:04:28.0
   4           OUT       2010-02-15 16:31:29.0       2010-07-29 11:03:28.0

2 个答案:

答案 0 :(得分:22)

使用:

  SELECT SUM(CASE WHEN p.problem_type = 'IN' THEN 1 ELSE 0 END) AS IN, 
         SUM(CASE WHEN p.problem_type = 'OUT' THEN 1 ELSE 0 END) AS OUT, 
         TO_CHAR(datetime, 'YYYY') AS year,
         TO_CHAR(datetime, 'MM') AS month
    FROM PROBLEM p
   WHERE p.DateTime >= TO_DATE('2010-01-01', 'YYYY-MM-DD') 
     AND p.DateTime < TO_DATE('2010-01-31', 'YYYY-MM-DD') 
GROUP BY TO_CHAR(datetime, 'YYYY'), TO_CHAR(datetime, 'MM')

你也可以使用:

  SELECT SUM(CASE WHEN p.problem_type = 'IN' THEN 1 ELSE 0 END) AS IN, 
         SUM(CASE WHEN p.problem_type = 'OUT' THEN 1 ELSE 0 END) AS OUT, 
         TO_CHAR(datetime, 'MM-YYYY') AS mon_year
    FROM PROBLEM p
   WHERE p.DateTime >= TO_DATE('2010-01-01', 'YYYY-MM-DD') 
     AND p.DateTime < TO_DATE('2010-01-31', 'YYYY-MM-DD') 
GROUP BY TO_CHAR(datetime, 'MM-YYYY')

参考:

答案 1 :(得分:6)

你可能想要像

这样的东西
SELECT SUM( (CASE WHEN problem_type = 'IN' THEN 1 ELSE 0 END) ) in,
       SUM( (CASE WHEN problem_type = 'OUT' THEN 1 ELSE 0 END) ) out,
       EXTRACT( year FROM DateTime ) year,
       EXTRACT( month FROM DateTime ) month
  FROM problem
 WHERE DateTime >= date '2010-01-01'
   AND DateTime < date '2010-01-31'
 GROUP BY EXTRACT( year FROM DateTime ),
          EXTRACT( month FROM DateTime )