I have 2 tables with duplicated values in one of the columns. I'd like to do a left join without taking rows, where mentioned column values duplicates. For example, i have table X:
id Value
A 2
B 4
C 5
and table Y:
id Value
A 2
A 8
B 2
I'm doing a LEFT JOIN:
SELECT*
FROM X LEFT JOIN Y ON X.id = Y.id;
Would like to have something like:
id Value
A 2 A 2
B 4 B 2
C 5
so that duplicated id (A 8) from table Y is not considered.
How do I prevent duplicate rows from joining multiple tables? Solution. Select column values in a specific order within rows to make rows with duplicate sets of values identical. Then you can use SELECT DISTINCT to remove duplicates.
Again, if we perform a left outer join where date = date, each row from Table 5 will join on to every matching row from Table 4. However, in this case, the join will result in 4 rows of duplicate dates in the joined DataSet (see Table 6).
In some cases, you need to join tables by multiple columns. In these situations, if you use only one pair of columns, it results in duplicate rows.
On the Design tab, click Run. Verify that the query returns the records that you want to delete. Click Design View and on the Design tab, click Delete. Access changes the select query to a delete query, hides the Show row in the lower section of the design grid, and adds the Delete row.
You can do it with GROUP BY
:
SELECT X.id, X.value, MIN(Y.value)
FROM X
LEFT JOIN Y ON X.id = Y.id
GROUP BY X.id, X.value
Note that it is not necessary to bring Y.id
into the mix, because it is either null
or equal to X.id
.
You are looking for GROUP BY to aggregate the Y table records, effectively collapsing them down to one row per id. I have chosen MIN but you could use SUM if they are integers like your example data.
SELECT
x.id , x.Value, y.id, min(y.value)
FROM
X LEFT JOIN Y ON X.id = Y.id
GROUP BY
x.id, x.value, y.id;
I have given exactly what you asked for. But in my opinion the y.Id is unnecessary in the select and group by list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With