I am a beginner in SQL, this is maybe a dumb question…
Table 1 (guide_book) :
ID | Table ID | Column A |
---|---|---|
0 | 0 | a |
1 | 0 | b |
2 | 0 | c |
3 | 0 | d |
Table 2 (adding) :
ID | Table ID | Column A |
---|---|---|
0 | 1 | b |
1 | 1 | c |
2 | 1 | d |
3 | 1 | e |
Query
SELECT Column A
FROM (
SELECT ID, Table ID, Column A
FROM guide_book
UNION ALL
SELECT ID, Table ID, Column A
FROM adding
) temp
GROUP BY Column A
having count(*)=1;
Output
Column A |
---|
a |
e |
Desired output
ID | Table ID | Column A |
---|---|---|
0 | 0 | a |
3 | 1 | e |
Since I have big table I need to know where are the results and in which table.
Thank you
2
Answers
You can make use of a windowed count here:
Your query groups by
Column A
and filters out unique values, but it doesn’t keep track of the originalID
andTable ID
. To get the desired output, you can use Common Table Expressions (CTEs).First, create a CTE named
Combined
that unions both tables (guide_book
andadding
). Then, create another CTE namedCounts
that counts the occurrences of each value inColumn A
.Finally, perform a SELECT query that joins the
Combined
andCounts
CTEs. Filter the rows where the count is 1 to get the unique values along with theirID
andTable ID
.Here’s an example:
This should give you the desired output with
ID
,Table ID
, andColumn A
for the unique values.