我想看看两个日期之间有多少天,不包括某些日期,这些日期取决于另一个表格中所述的值。
表1
ID in_date out_date
001 01/01/2017 01/05/2017
002 01/03/2017 01/05/2017
例如:
SELECT
id
,datediff(dd, t1.in_date, t1.out_date) as diff
FROM table1 t1
会带来
ID diff
001 4
002 2
但是,假设我有另一张桌子:
表2
date use
01/01/2017 Y
01/02/2017 N
01/03/2017 N
01/04/2017 Y
01/05/2017 Y
我希望在列use
下的Y日期之间看到日期。
因此,连接表1和2时的结果应该是:
ID diff
001 3
002 2
答案 0 :(得分:2)
您可以根据日期使用left join
:
select t.id, count(t2.date) as diff
from table1 as t
left join table2 as t2
on t2.date >= t.in_date
and t2.date <= t.out_date
and t2.[use] = 'Y'
group by t.id
rextester演示:http://rextester.com/XNX74966
返回:
+-----+------+
| id | diff |
+-----+------+
| 001 | 3 |
| 002 | 2 |
+-----+------+
答案 1 :(得分:1)
我会想到这样的事情:
SELECT t1.id,
t2.cnt as diff
FROM table1 t1 outer apply
(select count(*) as cnt
from table2 t2
where t2.date >= t1.in_date and t2.date <= t1.out_date and t2.use = 'Y'
) t2;
这是计算匹配的天数并省去datediff()
。
答案 2 :(得分:1)
我猜这个用例是: - 确定两个给定日期之间的工作日期数。 即table2包含所有假期。 如果我的假设是正确的,那么它最适合只存储table2中的假日和周末。即,不需要[use] =&#39; N&#39;在表2中。 在这个假设下继续,这就是我要做的事情:
Create function dbo.GetHolidayCount(@indate datetime, @outdate datetime)
returns int as
Begin
Declare @cnt int = 0
Select @cnt = count(*) from table2 where [date] >= @indate and [date] <= @outdate and [use]='N';
return @cnt
End
然后发出以下查询。
SELECT
id,
,datediff(dd, t1.in_date, t1.out_date) + 1 - dbo.GetHolidayCount(t1.in_date, t1.out_date) as diff
FROM table1 t1
我在结果中加1,因为在01/01/2017和01/05/2017之间的datediff会返回4;但你根据自己的要求需要5个。