I need to combine two tables by SQL server 2008.
table1:
col col1 col2_a
yyy ddd 1589
table2:
col col1 col2_b
yyy ddd 6231
The tables have same values for col and col1, only col2 are different. 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.
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
;
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;
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.