查找从月份到日期的总天数

时间:2017-01-24 04:26:38

标签: sql-server

我有这种假期表。

enter image description here

我希望找到完全休假日,月和年。

在什么条件下。

3 个答案:

答案 0 :(得分:0)

您可能需要考虑让每一天休假。使用范围将导致在该范围内占用假日甚至周末不计的天数。

答案 1 :(得分:0)

SELECT SUM(datediff(dd,from_date,to_date)) as  leaves , year(from_date) as [year],month(from_date) as [month] FROM 
(SELECT 1 as Id , 2 as created_by , '2016-11-16' as from_date , '2016-11-17' as to_date
UNION
SELECT 2 as Id , 2 as created_by , '2016-02-10' as from_date , '2016-02-12' as to_date
UNION
SELECT 3 as Id , 2 as created_by , '2016-04-20' as from_date , '2016-04-20' as to_date
UNIOn
SELECT 4 as Id , 2 as created_by , '2016-11-25' as from_date , '2016-11-26' as to_date
UNION
SELECT 5 as Id , 2 as created_by , '2016-11-26' as from_date , '2016-11-28' as to_date
UNION
SELECT 6 as Id , 2 as created_by , '2016-10-10' as from_date , '2016-10-11' as to_date
UNION
SELECT 7 as Id , 2 as created_by , '2016-12-30' as from_date , '2016-12-30' as to_date) a
group by year(from_date),month(from_date),year(to_date),month(to_date)

输出:

enter image description here

如果需要,您可以使用order by按月和按年排序。

答案 2 :(得分:0)

请尝试此查询,它还会考虑在年底休假,例如 2016-12-29至2017-01-05

create table #Test(id INT IDENTITY(1,1),from_date datetime,to_date datetime)

insert into #Test values('2016-11-16','2016-11-17')
insert into #Test values('2016-11-22','2016-11-25')
insert into #Test values('2016-09-22','2016-09-25')
insert into #Test values('2016-12-29','2017-01-05')
insert into #Test values('2017-01-08','2017-01-09')

select Sum(Leavestaken) as Leavestaken,LeaveYear,LeaveMonth from(select Sum(DATEDIFF(day,from_date,(case when YEAR(to_date)>YEAR(from_date) then DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, from_date) + 1, 0)) else to_date end))+1) Leavestaken,
YEAR(from_date) as LeaveYear,
MONTH(from_date) as LeaveMonth
from #Test
group by YEAR(from_date),MONTH(from_date)
union all
select Sum(DATEDIFF(day,(case when YEAR(to_date)>YEAR(from_date) then DATEADD(month, DATEDIFF(month, 0, to_date), 0) else from_date end),to_date)+1) Leavestaken,
YEAR(to_date) as LeaveYear,
MONTH(to_date) as LeaveMonth
from #Test
where YEAR(from_date)<>YEAR(to_date)
group by YEAR(to_date),MONTH(to_date)) as tbl
group by LeaveYear,LeaveMonth
order by LeaveYear 

--drop table #Test