简体   繁体   English

SQL - 连接或联合两个表检查重复项?

[英]SQL - Join or Union two tables checking for duplicates?

Let's say I have two tables as follows.假设我有两个表如下。

ALL_SPORTS ALL_SPORTS

ID  Name  Age  Sport        Result  Date    Weather
----------------------------------------------------
1   Jake   12  Basketball   Won     1/2/13  Sunny
2   Jill   13  Tennis       Lost    2/3/13  Sunny
3   Sam    14  Basketball   Won     4/5/14  Cloudy
4   Ann    15  Football     Won     6/7/18  Cloudy
5   Will   18  Track        Lost    11/12/13 Rainy

& &

Sports_results Sports_results

ID   Sport   Result  Date
----------------------------
1    Bball   W       1/2/13
2    Tn      L       2/3/13
2    Fball   L       1/2/14
3    Fball   L       4/9/14
3    Fball   W       4/9/14
4    Bball   L       8/9/18
5    Tk      L       11/12/13
8    pngpng  W       9/4/15

ALL_SPORTS has a lot more columns. ALL_SPORTS有更多的列。 Sport_Results is more specialized. Sport_Results更专业。 They both use different ways to show Sport name ( Sports_results uses shortened name) and result (Won and lost vs W and L).他们都使用不同的方式来显示运动名称( Sports_results使用缩写名称)和结果(Won and Sports_results vs W and L)。

There is some overlap between the tables but each might contain something not contained in the other table and vice versa.表之间存在一些重叠,但每个表可能包含其他表中未包含的内容,反之亦然。

I need to make a third table called ALL_RESULTS which gets all the results from ALL_RESULTS and Sports_Results checking for duplicate results.我需要创建一个名为 ALL_RESULTS 的第三个表,它从 ALL_RESULTS 和 Sports_Results 检查重复结果中获取所有结果。 It should get the following values from the tables.它应该从表中获取以下值。

ALL_RESULTS (desired results) ALL_RESULTS (预期结果)

ID  Name  Age  Sport        Result  Date    Weather
---------------------------------------------------
(From ALL_SPORTS)
1   Jake   12  Basketball   Won     1/2/13  Sunny
2   Jill   13  Tennis       Lost    2/3/13  Sunny
3   Sam    14  Basketball   Won     4/5/14  Cloudy
4   Ann    15  Football     Won     6/7/18  Cloudy
5   Will   18  Track        Lost    11/12/13 Rainy

(From Sports_results)
ID   Sport   Result  Date
-----------------------------
3    Fball   L       4/9/14
3    Fball   W       4/9/14
4    Bball   L       8/9/18
8    pngpng  W       9/4/15

Currently I'm doing a Union but since the formats of values contained in both tables is different and ALL_SPORTS contains more columns, Union cannot find duplicates.目前我正在做一个联合,但由于两个表中包含的值的格式不同,并且ALL_SPORTS包含更多列,联合找不到重复项。

Would love some tips!会喜欢一些提示! TIA TIA

Just select the common columns and convert to the same format:只需选择常见的列并转换为相同的格式:

select a.ID, a.Sport, a.Result, a.Date
from all_sports a
union   -- on purpose to remove duplicates
select sr.ID, sr.Sport,
       (case sr.Result when 'W' then 'Won' when 'L' then 'Lost' end), 
       sr.Date
from Sports_results sr;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM