简体   繁体   中英

SQL query with UNION or INTERSECT

I have 2 tables in SQL like below and need to run some tests queries on the data. The tables are with some sample data:

Table A
ID       groupName    value
id2000   groupA       1
id2000   groupA       2
id2000   groupA       3
id3000   groupB       1
id3000   groupB       2

Table B
ID       groupNameB    valueB
id2000   groupA        1
id2000   groupA        2
id2000   groupA        -9
id3000   groupB        1
id3000   groupB        -9

The tables are similar but actually are different (they have different data and I just shortened it for stack overflow).

What I need is a year that joins the two but gives me the values that are in Table A but not in table B.

So using the above data I would get a resultset of:

id2000  groupA 3
id3000  groupB 2

Its like a NOT UNION I guess?

You want to use EXCEPT .

It removes the rows from the first query that are also in the second query. It does not return rows in query2 that were not in query1.

select id, groupName, value
from tableA
except
select id, groupNameB, valueB
from tableB
select a.ID, a.groupName, a.Value 
from [Table A] a
left join [Table B] b
on a.ID = b.ID
and a.groupName = b.groupNameB
and a.Value = b.ValueB
where b.ID is null

If I understand correctly this would work. At least it does with my sample data.

select Id, groupName, value
  FROM tableA 
EXCEPT
select Id, groupName, value
  FROM tableB

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.

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