Sql 选择与内部联接中的日期范围相对应的行
我在一个表(表A)中有如下数据:Sql 选择与内部联接中的日期范围相对应的行,sql,sql-server,tsql,Sql,Sql Server,Tsql,我在一个表(表A)中有如下数据: id datestart dateend department 1 2008-01-01 9999-12-31 fmcg 2 2010-02-01 2011-04-09 sales . . . . . . . . y
id datestart dateend department
1 2008-01-01 9999-12-31 fmcg
2 2010-02-01 2011-04-09 sales
. . . .
. . . .
yearmonth id
2010-01-01 1
2010-01-01 2
2010-02-01 1
2010-02-01 2
. .
. .
id datestart dateend department
2 2011-04-10 9999-12-31 fmcg
有数百万行,9999-12-31表示当前日期。我还有一张表(表B),看起来像:
id datestart dateend department
1 2008-01-01 9999-12-31 fmcg
2 2010-02-01 2011-04-09 sales
. . . .
. . . .
yearmonth id
2010-01-01 1
2010-01-01 2
2010-02-01 1
2010-02-01 2
. .
. .
id datestart dateend department
2 2011-04-10 9999-12-31 fmcg
表A中的id可以有多行,例如,id 2在sales中,但还有一行类似于:
id datestart dateend department
1 2008-01-01 9999-12-31 fmcg
2 2010-02-01 2011-04-09 sales
. . . .
. . . .
yearmonth id
2010-01-01 1
2010-01-01 2
2010-02-01 1
2010-02-01 2
. .
. .
id datestart dateend department
2 2011-04-10 9999-12-31 fmcg
这意味着他们转向了快速消费品售后服务(日期没有重叠)
我想做的是在表B中添加另一列,显示员工在yearmonth的工作地点:
yearmonth id department
2010-01-01 1 fmcg
2010-01-01 2 NULL
2010-02-01 1 fmcg
2010-02-01 2 sales
. .
. .
2011-05-01 1 fmcg
2015-05-01 2 fmcg
抱歉,我无法发布我使用过的确切代码,因为它在我的工作计算机上,并且我目前正在使用另一台计算机,但它看起来类似于:
select a.*
, case when b.dateend = '9999-12-31' then b.department
when a.yearmonth < b.dateend then b.department else b.department end as department
from table_a a
inner join table_b b on a.id = b.id
(apologies if missing crucial bits, am going by memory)
yearmonth id department
2010-01-01 1 fmcg
2010-01-01 2 NULL
2010-02-01 1 fmcg
2010-02-01 2 sales
2010-02-01 2 fmcg
. .
. .
2011-05-01 1 fmcg
2015-05-01 2 fmcg
2015-05-01 2 sales
但我很难理解什么会起作用。如果你能帮助我,我将不胜感激 试试这个:
SELECT B.ID, B.YearMonth, ApplyResult.Department FROM TableB B
OUTER APPLY(
SELECT A.Department FROM TableA A
WHERE A.ID = B.ID AND B.YearMonth BETWEEN A.DateStart AND A.DateEnd
) ApplyResult
或者这个:
SELECT B.ID, B.YearMonth, A.Department FROM TableB B
LEFT OUTER JOIN TableA A On A.ID = B.ID AND B.YearMonth BETWEEN A.DateStart AND A.DateEnd
表a:
ID DateStart DateEnd Department
1 2008-01-01 9999-12-31 DepA
2 2010-02-01 2010-03-09 DepA
2 2010-03-10 9999-12-31 DepB
表B:
ID YearMonth
1 2010-01-01
2 2010-01-01
1 2010-02-01
2 2010-02-01
1 2010-03-01
2 2010-03-01
1 2010-04-01
2 2010-04-01
输出:
ID YearMonth Department
1 2010-01-01 DepA
2 2010-01-01 NULL
1 2010-02-01 DepA
2 2010-02-01 DepA
1 2010-03-01 DepA
2 2010-03-01 DepA
1 2010-04-01 DepA
2 2010-04-01 DepB
只需将日期条件添加到
on
子句中:
select a.*, b.department
from table_a a inner join
table_b b
on a.id = b.id and
b.yearmonth between a.datestart and a.dateend
如果一个月中旬发生了什么事情,你想显示什么,比如说ID 2个月,这将是一个月开始的库存,所以2010-04-01,ID 2仍然在销售,但截至2010-05-01,它们是FMCGES的一部分!!噢,天哪,非常感谢你,这正是我想要的。@Linda T,我在回答中添加了第二个问题。看起来好多了。请也检查一下。