I have a table with below structure:
create table A_TEST
(
order_num int,
product_name varchar(50),
product_amount int,
product_price int
);
Sample data :
insert into a_test (order_num , product_name , product_amount , product_price)
values (1,'APPLE',1000,2000),
(1,'APPLE',2000,5000),
(1,'APPLE',4000,3000),
(2,'ORANGE',280,3000),
(2,'APPLE',200,3000),
(3,'BANANA',2000,3000),
(3,'APPLE',200,3000),
(4,'POTATO',123,3000),
(4,'POTATO',2000,3000),
(4,'APPLE',2000,3000),
(5,'APPLE',360,3000),
(5,'POTATO',2000,3000),
(5,'TOMATO',360,3000),
(5,'BANANA',123,3000),
(5,'ORANGE',126,3000);
What I want is to find those order_num
s that have different product_name
s so that no two product_name for one order_num should be the same . The desired result would be (2,3,5)
. I tried to solve this with Exists
but it won't return the correct result.
SELECT *
FROM A_TEST A
WHERE EXISTS (SELECT *
FROM A_TEST B
WHERE A.order_num = B.order_num
AND A.product_name <> B.product_name);
I know why this does not return the correct result. The reason is that if it finds at least one product_name which is different from another one, it will return it's order_num. I was wondering if you could suggest better solutions.
Thanks in advance
Best Answer
Classic solution:
Custom solutions:
...
fiddle
fiddle