Script setup
CREATE TABLE ORDERS (cust INT, brand VARCHAR(100)) INSERT INTO ORDERS VALUES (1, 'Sony') INSERT INTO ORDERS VALUES (1, 'Sony') INSERT INTO ORDERS VALUES (1, 'Sony') INSERT INTO ORDERS VALUES (1, 'Hp') INSERT INTO ORDERS VALUES (1, 'Hp') INSERT INTO ORDERS VALUES (2, 'Sony') INSERT INTO ORDERS VALUES (2, 'Sony') INSERT INTO ORDERS VALUES (2, 'Hp') INSERT INTO ORDERS VALUES (2, 'Hp') INSERT INTO ORDERS VALUES (2, 'Hp') INSERT INTO ORDERS VALUES (2, 'Hp') INSERT INTO ORDERS VALUES (3, 'Sony') INSERT INTO ORDERS VALUES (3, 'Sony') INSERT INTO ORDERS VALUES (3, 'Sony') INSERT INTO ORDERS VALUES (3, 'Hp') INSERT INTO ORDERS VALUES (3, 'Hp')
Request
Method 1
select sony.custId from (select cust as custId, Brand, count(*) as count from orders where Brand = 'Sony' group by cust, brand) Sony inner join (select cust as custId, Brand, count(*) as count from orders where Brand = 'Hp' group by cust, brand) Hp on sony.custId = hp.CustId Where sony.count > 2 and hp.count < 5
It is good for you to understand the attitude. Here is another way
Method 2
select cust from orders group by cust, brand having count(case brand when 'Sony' then 'x' end) > 2 and count(case brand when 'Hp' then 'x' end) < 5
The time is approximately the same - of course, it will vary depending on the amount of data, indices, etc. Use the Sql script to verify the execution plan. It seems that more is happening in the first method. But this does not mean that when used in production it will be much worse.
source share