简体   繁体   English

SQL Server 2008将两个表合并为一个,但得到重复的行

[英]SQL server 2008 merge two tables into one but get duplicated rows

I need to combine two tables by SQL server 2008. 我需要通过SQL Server 2008合并两个表。

table1: 表格1:

 col  col1  col2_a
 yyy  ddd   1589

table2: 表2:

 col  col1  col2_b
 yyy  ddd   6231

The tables have same values for col and col1, only col2 are different. 这些表的col和col1值相同,只有col2不同。 I need to merge them into one table. 我需要将它们合并到一张表中。

SELECT a.col , a.col1, a.col2_a, b.col2_b
 FROM table1 as a, table2 as b
 WHERE a.col = b.col AND a.col1 = b.col1

But, this give me 4 duplicated rows for each col and col1 combination. 但是,这给我每个col和col1组合的4个重复行。

Any help would be appreciated. 任何帮助,将不胜感激。

I expect : 我预计 :

 col  col1  cola  colb
 yyy  ddd   1589  6231

If you just plain want to eliminate exact duplicate rows , you can simply use DISTINCT ; 如果您只是想消除确切的重复行 ,则可以简单地使用DISTINCT ;

SELECT DISTINCT a.col , a.col1, a.col2_a, b.col2_b
FROM table1 as a
JOIN table2 as b
  ON a.col = b.col AND a.col1 = b.col1

If you instead want only one value (for example the max one) from table2 even though several rows match, you can select rows from table1 and only the max matching value of b.col2 from table2; 如果您希望从table2中仅获得一个值(例如,最大值),即使有几行匹配,则可以从table1中选择行,而从table2中仅选择b.col2的最大匹配值;

SELECT DISTINCT a.col , a.col1, a.col2_a, MAX(b.col2_b) col2_b
FROM table1 as a
JOIN table2 as b
  ON a.col = b.col AND a.col1 = b.col1
GROUP BY a.col, a.col1, a.col2

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

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