Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Conta il numero di giorni di noleggio in JAN

Qualcosa del genere?

declare @t table (id int, tool  varchar(10),    on_hire date,    off_hire date);
insert into @t values
(1,1,'2016-01-01','2016-01-10'),
(2,1,'2016-01-15','2016-01-20'),
(3,2,'2015-12-01','2016-01-10'),
(4,3,'2016-01-20','2016-02-10'),
(5,4,'2015-01-01','2017-01-10')


select tool,  sum(datediff(d,on_hire,off_hire)) + 1 dayshired
from
(
select tool,
        case 
            when on_hire < '2016-01-01' then '2016-01-01'
            else on_hire 
        end as on_hire,
        case 
            when off_hire > '2016-01-31' then '2016-01-31'
            else off_hire 
        end as off_hire         
from @t
) s
group by s.tool