I would love some help to solve my problem below please!
I have two SQL Server tables which I would like to merge into one result table. Table 1 has larger intervals (DistanceFrom - DistanceTo) than Table 2 so I am dealing with overlapping intervals. Sometimes it is perfect match for DistanceFrom and DistanceTo but other times not.
I would like to display the Table1.code associated to each Sample in the result table, knowing the DistanceFrom and DistanceTo can vary.
Table 1:
Table 2:
Desired result table:
Any help will be greatly appreciated!
Thanks
I managed to merge the 2 tables but always end up with some NULL in my Table1.Code result table as I struggle to split the intervals from Table 1 when required. The only time I don't have NULL is when the DIstanceFrom and Distance2 from table 1 are matching the ones from Table2.
Or I have managed to merge but I am missing some 'Sample' (missing the intervals not matching DistanceFrom and Distance To basically)
----To Ravi Hi Ravi and thanks for your quick answer. I think I may not have been clear enough and below is a better example with the results expected: So far I have managed to get most of my intervals using a different query but I have intervals still missing. The sample should be duplicated in some occasion like for U2 but the matching distancefrom and distanceTo should be different when there is a sample reapeat due to an overlapping code if it makes sense?
CREATE TABLE table1 ( Code VARCHAR(10) NULL ,DistanceFrom INT NULL ,DistanceTo INT NULL )
CREATE TABLE table2 ( Sample VARCHAR(10) NULL ,DistanceFrom INT NULL ,DistanceTo INT NULL ) INSERT INTO table1 VALUES ('A',68.04 ,74.58), ('B',74.58 ,74.85), ('C', 74.85, 75.07),('D', 75.07, 81.07)
INSERT INTO table2 VALUES ('U1',74 ,74.58), ('U2',74.58 ,75.07), ('U3', 75.07, 76), ('U4',76 ,77)
Below would be the results I would like to get:
Sample DistanceFrom DistanceTo Table1.Code U1 74 74.58 A U2 74.58 74.85 B U2 74.85 75.07 C U3 75.07 76 D U4 76 77 NULL
1条答案
按热度按时间mrfwxfqh1#
Here is the query:
DDL
Select Query
Explanation
DistanceFrom - DistanceTo
andSDistanceFrom - SDistanceTo
SELECT:
RDistanceFrom
: Maximum ofDistanceFrom
andSDistanceFrom
RDistanceTo
: Minimum ofDistanceTo
andSDistanceTo
Please check SQL Fiddle and tweak your query incase it needs any change.
Regards, Ravi