SQL显示在特定日期之前和之前租用的所有项目

时间:2017-01-18 09:34:21

标签: sql sql-server sql-server-2008

我有一张桌子上有许多工具,包括雇用日期和雇用日期。

我想展示一个月内雇用的所有工具。

例如

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

有可能获得在JAN开始的所有内容都有一个WHERE但我需要捕获工具2,它也开始于DEC但是在JAN结束

有什么想法吗?

非常感谢帮助,欢呼声

5 个答案:

答案 0 :(得分:2)

带我回去,但这就是你想在这段时间内展示一切租赁的所有内容,包括非退货项目

select *
from MyTable
where on_hire < @EndDate
and (off_hire >= @StartDate or off_hire is null)

对于后续工作,每个工具的总天数

with CTE as
(
    select *
    from MyTable
    where on_hire < @EndDate
    and (off_hire >= @StartDate or off_hire is null)
)
select Tool,
       sum(datediff(dd,
                    case
                      when off_hire > @EndDate then @EndDate
                      when off_hire is null then @EndDate
                      else off_hire
                    end,
                    case
                      when on_hire < @StartDate then @StartDate
                      else on_hire
                    end)) as DaysOnHire
from CTE
froup by Tool

答案 1 :(得分:1)

试试这个

SELECT * FROM TABLE1 
WHERE on_hire BETWEEN @startdate AND @enddate 
OR off_hire BETWEEN @startdate AND @enddate 

答案 2 :(得分:0)

尝试此查询

create table #yourtable (tools varchar(50),on_hire datetime,off_hire datetime)

insert into #yourtable

select 'tool1'  ,'2016-01-02'  ,'2016-01-15' 
union all
select 'tool2'  ,  '2015-12-16' ,'2016-01-16'
union all
select 'tool3' ,   '2016-01-05', '2016-02-20'

select * from #yourtable
where datepart(mm,on_hire)='01' and tools<>'tool2'
union all
select * from #yourtable
where datepart(mm,on_hire)='12' and datepart(mm,off_hire)='01' and tools='tool2'

答案 3 :(得分:0)

两行x1-x2y1-y2(日期范围等)在以下时间相交:

x1 <= y2 and y1 <= x2

所以:

select * from table
where on_hire <= @enddate and @startdate <= off_hire

答案 4 :(得分:-1)

应该有三种选择:

1.     |______| --hire time
    s|—————|e

2.     |______| --hire time
           s|—————|e

3.     |______|--hire time
    s|—————————————|e


4.     |______|--hire time
        s|———|e    --included in 2 and 3
    DECLARE @startdate date = '01/01/2016', @enddate DATE = '01/31/2016'
    ;WITH tb(tool,on_hire,off_hire)AS(
        SELECT 'tool 1','01/02/2016','01/15/2016'  UNION                            
        SELECT 'tool 2','12/16/2015','01/16/2016'  UNION    
        SELECT 'tool 3','01/05/2016','02/20/2016'
    )
    SELECT * FROM tb
    WHERE 
    DATEDIFF(d,tb.on_hire,@startdate)>0 AND DATEDIFF(d,@startdate,tb.off_hire)>0
    OR DATEDIFF(d,tb.on_hire,@enddate)>0 AND DATEDIFF(d,@enddate,tb.off_hire)>0
    OR DATEDIFF(d,tb.on_hire,@startdate)>0 AND DATEDIFF(d,tb.off_hire,@enddate)>0