i have a question:
I want to join two SQL querys into one query using UNION to avoid duplicates, but i need to know if the data comes from the fisrt select query or from the second select query.
Sample data:
A TABLE B TABLE
-----------------------------------------------------------------------------
01 JOHN 01 JOHN
02 JUAN 02 PETER
03 MARTIN 03 MARTIN
I have something like this:
Select A.code,A.name from A where some conditions
unión
Select B.code,B.name from B where diferent conditions
RESULT TABLE
01 JOHN
02 JUAN
02 PETER
03 MARTIN
This Works fine, but now if i want to know if the data comes from first query or from the second i think something like this:
Select A.code,A.name, 'A' from A where some conditions
unión
Select B.code,B.name, 'B' from B where diferent conditions
RESULT TABLE
01 JOHN 'A'
01 JOHN 'B'
02 JUAN 'A'
02 PETER 'B'
03 MARTIN 'A'
03 MARTIN 'B'
But don't avoid "duplicates" because 'A' is diferent to 'B', so the question is, can i do something so that they don't compare the 'A' with the 'B'?, is another way to obtain the expected result?
EDIT:
The expected result
01 JOHN 'A'
02 JUAN 'A'
02 PETER 'B'
03 MARTIN 'A'
Using UNION on Multiple FieldsWe can apply UNION on multiple columns and can also order the results using the ORDER BY operator in the end.
Use the relational operators != or <> to exclude rows in a WHERE clause.
UNION or UNION ALL have the same basic requirements of the data being combined: There must be the same number of columns retrieved in each SELECT statement to be combined. The columns retrieved must be in the same order in each SELECT statement.
Here's another way of doing it:
SELECT code, name, MIN(SourceTable) AS SourceTable
FROM (
SELECT code, name, 'A' AS SourceTable
FROM A
UNION
SELECT code, name, 'B' AS SourceTable
FROM B) t
GROUP BY code, name
ORDER BY code
Demo here
or perhaps:
SELECT code, name, SourceTable
FROM (
SELECT code, name, SourceTable,
ROW_NUMBER() OVER (PARTITION BY code, name
ORDER BY SourceTable) AS rn
FROM (
SELECT code, name, 'A' AS SourceTable
FROM A
UNION ALL
SELECT code, name, 'B' AS SourceTable
FROM B) t) AS x
WHERE x.rn = 1
Demo here
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