0

嗨,我想找到两个月的总天数,并按月拆分天数..例如... 2013 年 2 月 26 日到 2013 年 2 月 3 日 2 月这里显示 2 天休假,但 3 月我不会显示总休假..这是我的查询..任何人都可以更正我的查询..它只显示二月天,三月天在这里不显示..

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'
4

1 回答 1

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 小提琴

于 2013-02-11T10:52:54.693 回答