我的结果集看起来像是:
[DateField ][Hour][Value]
2014-10-01 1 200
2014-10-01 2 600
我需要在另一个表中添加一些其他列,例如:
[DateField ][Hour][Value][T2Value1][T2Value2]
2014-10-01 1 200 Off 5
2014-10-01 2 600 Off 7
如果表1中的Value字段落在表2的RangeValue1和RangeValue2之间,我需要表2中的T2Value1和T2Value2。
[Id][T2Value1][T2Value2][RangeValue1][RangeValue2]
1 Off 5 1 500
2 Off 7 501 1000
我已开始查询
select datefield, hour, value, t2value1, t2value2 from
(
-- inner query that returns datefield, hour, value
) Table1, Table2
但不知道从哪里拿走它。非常感谢任何帮助,谢谢!
答案 0 :(得分:2)
见这个简单的例子:
declare @Values as table
(
Name varchar(10) not null
,Value int not null
)
declare @Ranges as table
(
Grade char(1) not null
,v0 int not null
,v1 int not null
)
insert into @Values
values
('Albert', 33)
,('Bob', 133)
,('Carl', 233)
insert into @Ranges
values
('A',0,100)
,('B',100,200)
,('C',200,300)
select * from @Values v
join @Ranges r on r.v0 <= v.Value and v.Value < r.v1
正如您所看到的,可以在join子句中添加一些更复杂的条件,在这种情况下是一个范围条件
导致:
Name Value Grade v0 v1
---------- ----------- ----- ----------- -----------
Albert 33 A 0 100
Bob 133 B 100 200
Carl 233 C 200 300
答案 1 :(得分:1)
简单的连接可以满足您的需求。开启条件比正常情况复杂一点,但并不多。
select t1.DateField, t1.Hour, t2.t2value1, t2.t2value2
from table1 t1
inner join table2 t2 on t2.RangeValue1 <= t1.Value and t1.Value <= t2.RangeValue2