简体   繁体   中英

Filter rows in SQL by sub-query/ joins

Here is a table of user, product and month.

CREATE TABLE USERS (user VARCHAR(1),product VARCHAR(1),month INT);
INSERT INTO USERS (user,product,month) VALUES 
("A","X",9),("A","X",10),("A","X",10),("A","Y",11),
("B","Y",12),("B","X",10),("C","X",10),("D","Z",11),("D","X",9);

How do I count the number of users of a certain product only (possibly also in a specific month)?

Join a derived table where you get the users only using product X by using aggregation and checking if the minimum product equals the maximum product. Then use count(DISTINCT ...) .

SELECT count(DISTINCT u1.user)
       FROM USERS u1
            INNER JOIN (SELECT u2.user
                               FROM USERS u2
                               GROUP BY u2.user
                               HAVING min(u2.product) = max(u2.product)
                                      AND min(u2.product) = 'X') upx
                       ON upx.user = u1.user;

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