我想计算明确列出的月份总数

时间:2014-03-09 07:55:17

标签: mysql sql

empid   leavefrom     leaveto      leaverequested    
 1      3/3/2014     4/3/2014       2   
 1      7/3/2014     8/3/2014       2
 1      31/3/2014    1/4/2014       2
 1      10/4/2014    11/4/2014      2

我想计算叶子请求列的总和。输出:

march -  5 days
april -  3 days

到目前为止,这是我的SQL查询:

select Emp_id
  ,datename(month,leave_from) as [First]
  ,datename(month,leave_to) as Last
  ,count(DATEDIFF(Day, leave_from, leave_to)+1) as [Total Leave]
  ,sum(DATEDIFF(Day, leave_from, leave_to)+1) as [Total Days]
from emp_leave
group by Emp_id
        ,datename(month,leave_from)
        ,datename(month,leave_to);

任何人都可以帮我获得这个输出吗?

1 个答案:

答案 0 :(得分:0)

一种方法

WITH n AS 
(
  SELECT 0 n
  UNION ALL
  SELECT n + 1 FROM n WHERE n < 32 -- adjust as needed to max months that a leave can possibly span
), base AS 
( 
  SELECT empid, 
         DATEADD(mm, n.n, DATEADD(mm, DATEDIFF(mm, 0, leavefrom), 0)) basemonth,
         CASE WHEN leavefrom > DATEADD(mm, n.n, DATEADD(mm, DATEDIFF(mm, 0, leavefrom), 0)) 
              THEN leavefrom 
              ELSE DATEADD(mm, n.n, DATEADD(mm, DATEDIFF(mm, 0, leavefrom), 0))
         END sdate, 
         CASE WHEN leaveto < DATEADD(mm, n.n, DATEADD(mm, DATEDIFF(mm, 0, leavefrom) + 1, -1)) 
              THEN leaveto 
              ELSE DATEADD(mm, n.n, DATEADD(mm, DATEDIFF(mm, 0, leavefrom) + 1, -1)) 
         END edate
    FROM emp_leave JOIN n
      ON n.n <= DATEDIFF(month, leavefrom, leaveto)
)
SELECT empid, 
       YEAR(basemonth) year,
       DATENAME(mm, basemonth) month,
       SUM(DATEDIFF(dd, sdate, edate) + 1) total
  FROM base
GROUP BY empid, basemonth
ORDER BY empid, base month

输出:

| EMPID | YEAR | MONTH | TOTAL |
|-------|------|-------|-------|
|     1 | 2014 | March |     5 |
|     1 | 2014 | April |     3 |

这是 SQLFiddle 演示