Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Statement to Compare rows

Tags:

sql

join

compare

I've got a table that stores Product #s, Client Name, and Region. So I can query for all products for a particular client in a specific region using this one single table.

I'm trying to write a query that will allow me to see which products the client has in 1 region but not the other and vise-versa (compare regions). In other words, can I see all products in the north not in the south, and all products in the south not in the north, for a particular client.

I'm pretty sure this would be very easy if it were 2 separate queries, but I'm trying to do it in a single query. Is it possible?

Product          Client          Region
500              1               North
500              1               South
501              1               North
502              1               South
503              1               North
503              1               South

Results for the above data would indicate that Client 1 has Product 501 in the North, but not the South as well as Product 502 in the South but not the North. Products 500 and 503 are ignored since they're in both Regions.

Product          Client          Region
501              1               North
502              1               South
like image 777
jake_nerdnest Avatar asked Jul 05 '26 01:07

jake_nerdnest


1 Answers

Here's one way:

Select product, client, region
From yourTable t
Where region in('north','south')
  And not exists(
    Select product, client, region
    From yourTable tt
    Where t.region <> tt.region
      And t.client = tt.client
      And t.product = tt.product
    )
like image 185
RBarryYoung Avatar answered Jul 06 '26 20:07

RBarryYoung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!