[英]How to get values based on two dates columns from a different table?
I have two tables, table A has the Stock details and table B has the rates for certain product types valid for different periods.我有两个表,表 A 包含库存详细信息,表 B 包含适用于不同时期的某些产品类型的费率。
create table tableA(
Id int,
StockId int,
AsOfDate date,
Type_1_Bit bit,
Type_2_Bit bit,
Type_3_Bit bit,
PurchaseDate date);
go
Create table TableB(
Id int,
BeginDate date,
EndDate date,
Rates decimal(8,5),
Type_1_Bit bit,
Type_2_Bit bit,
Type_3_Bit bit);
go
I tried doing a left join with conditions but this logic gives me null rates.我尝试使用条件进行左连接,但此逻辑给了我空率。 My resulting table should be like this--
我的结果表应该是这样的——
select
a.Id,
a.StockId,
a.PurchaseDate,
a.AsOfDate,
b.Rates,
b.Type_1_Bit,
b.Type_2_Bit,
b.Type_3_Bit
into #temp
from tableA a
left join TableB b
on b.Type_1_Bit = a.Type_1_Bit
and b.Type_2_Bit = a.Type_2_Bit
and b.Type_3_Bit = a.Type_3_Bit
and a.AsOfDate >= b.BeginDate
and a.AsOfDate <= b.EndDate
What am I doing wrong here?我在这里做错了什么?
The first thing I notice is you're doing:我注意到的第一件事是你在做什么:
and a.AsOfDate >= b.BeginDate
and a.AsOfDate <= b.EndDate
both BeginDate
and EndDate
need to be equal? BeginDate
和EndDate
需要相等吗? If not, try using the between
operator instead.如果没有,请尝试使用
between
运算符。
a.AsOfDate between b.BeginDate and b.EndDate
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.