如何在两个月之间分割月份的天数

时间:2013-02-11 09:39:54

标签: sql-server

嗨我想找到两个月的总天数并将月份分为两个月......例如...... 2013年2月26日至3月3日至2013年3月3日 在这里2月份它显示2天休假但是3月我不会显示总休假..这是我的查询..任何人都可以更正我的查询...仅显示febraury天,这里没有显示行军日.. < / p>

SELECT  month(fdate) as Month_Number
        , datename(month, fdate) as Month
        , case when month(fdate) <> month(tdate) then 
            datediff(day, fdate, DATEADD(month, ((YEAR(fdate) - 1900) * 12) + MONTH(fdate), -1)) 
          else 
            datediff(day, fdate, tdate) 
          end as Leaves 
from    test 
where   empid like '112'

1 个答案:

答案 0 :(得分:0)

试试这个,它会显示每个月的天数:

SELECT  *
        , DATEADD(DAY, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, t.fdate) + 1, 0)) Last_In_Month_Of_Beginning
        , DATEADD(MONTH, DATEDIFF(MONTH, 0, t.tdate), 0) First_In_Month_Of_End
INTO    #temp1
FROM    test t
WHERE   empid LIKE '112'

SELECT  number Month_Number
        , CASE 
            WHEN MONTH(fdate) = MONTH(tdate) THEN DATEDIFF(DAY, fdate, tdate) - 1
            WHEN MONTH(Last_In_Month_Of_Beginning) = number THEN DATEDIFF(DAY, fdate, Last_In_Month_Of_Beginning)
            WHEN MONTH(First_In_Month_Of_End) = number THEN DATEDIFF(DAY, First_In_Month_Of_End, tdate)
          END Leave
INTO    #temp2
FROM    #temp1 a
JOIN    master..spt_values v ON
        v.type = 'P'
AND     v.number BETWEEN MONTH(a.Last_In_Month_Of_Beginning) AND MONTH(a.First_In_Month_Of_End)

SELECT  Month_Number
        , SUM(Leave) Leaves
FROM    #temp2
GROUP BY Month_Number

这是 SQL Fiddle