跟进我之前的问题
SQL Show all items that are on hire before and up until a certain date
我现在只想在设定的变量期间计算出租的日子。
我使用
计算出工具出租的天数 ,(CASE WHEN off_hire = '21121231'
THEN datediff(DAY, on_hire, GETDATE())
ELSE datediff(DAY, on_hire, offhire)+1
END) AS 'DAYS_OF_RENTAL'
21121231是工具仍在使用的日期。
我正在努力计算出仅使用
在JAN租用的天数 ,(CASE WHEN (on_hire > @startdate) AND off_hire > @end_date
THEN datediff(DAY, @startdate, @enddate )
ELSE datediff(DAY, on_hire, off_hire)+1
END) AS 'CALC_DAYS_ON_HIRE'
这显然不起作用,但这是我此刻一直在尝试的路线。
示例数据
tool on_hire off_hire
tool 1 02/01/2016 15/01/2016
tool 2 16/12/2015 16/01/2016
tool 3 05/01/2016 20/02/2016
我有一个变量set @startdate = 20160101
和@enddate = 20160131
非常感谢任何帮助,我仍在学习,但到达那里: - )
干杯
答案 0 :(得分:0)
这样的东西?
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
答案 1 :(得分:0)
我最终这样做了
,(CASE WHEN (on_hire < @startdate) AND off_hire > @enddate
THEN datediff(DAY, @startdate, @enddate )+1
WHEN (on_hire < @startdate) AND off_hire < @enddate
THEN datediff(DAY, @startdate, off_hire)+1
WHEN (on_hire > @startdate) AND off_hire > @enddate
THEN datediff(DAY, on_hire, @enddate )
WHEN (on_hire > @startdate) AND off_hire < @enddate
THEN datediff(DAY, on_hire, off_hire )
END) AS 'CALC_DAYS_ON_HIRE'