Join tables while returning distinct values from the second table

时间:2015-07-31 19:31:24

标签: sql join duplicates

I would like to join two tables joined by a date value. Below are the tables I would like to join.

      **Table 1**                               **Table2**
ID  Name    Date    AnalysisID              ID  Name    Date    FileID
1   Test   8/1/14       50                  1   Test   8/1/14      10
1   Test   8/1/14       55                  1   Test   8/1/14      12
1   Test   8/1/14       64
1   Test   8/1/14       67       

When attempting to join, I'll get repeating FileIDs for each AnalysisID using the following sql

select t1.id
, t1.name
, t1.date
, t1.analysisid
, t2.fileid
from Table_1 t1
, Table_2 t2
where t2.id = t1.id
and t2.name = t1.name
and t2.date = t2.date

**Joined Table**

ID  Name    Date    AnalysisID   FileID
1   Test   8/1/14       50         10
1   Test   8/1/14       50         12
1   Test   8/1/14       55         10
1   Test   8/1/14       55         12
1   Test   8/1/14       64         10
1   Test   8/1/14       64         12
1   Test   8/1/14       67         10
1   Test   8/1/14       67         12

My desired results would look like the Following

**Desired Table**
ID  Name    Date    AnalysisID   FileID 
1   Test   8/1/14       50         10 
1   Test   8/1/14       55         12 
1   Test   8/1/14       64
1   Test   8/1/14       67 

I'm not sure how to accomplish this. I've tried removing duplicated using row_number solutions but I just get a really choppy looking table. Is there a better way to use joins here? Any help is appreciated. Thanks

1 个答案:

答案 0 :(得分:0)

The results you get are correct. You are getting a catersian product for the columns analysisid and fileid. You should only select one column to avoid this. However, try to use the ANSI-SQL join syntax when joining tables like:

select t1.id
, t1.name
, t1.date
, t1.analysisid
, NULL as fileid
from Table_1 t1 JOIN Table_2 t2
ON t2.id = t1.id
and t2.name = t1.name
and t2.date = t2.date
UNION
select t1.id
, t1.name
, t1.date
, NULL
, t2.fileid
from Table_1 t1 JOIN Table_2 t2
ON t2.id = t1.id
and t2.name = t1.name
and t2.date = t2.date

Edit: This is the closest you can get to your desired result which would look like

 **Desired Table**
ID  Name    Date    AnalysisID   FileID 
1   Test   8/1/14       50         
1   Test   8/1/14       55          
1   Test   8/1/14       64
1   Test   8/1/14       67 
1   Test   8/1/14                 10 
1   Test   8/1/14                 12