[英]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.加入一个派生表,通过使用聚合并检查最小产品是否等于最大产品,您可以在其中获得仅使用产品X
的用户。 Then use count(DISTINCT ...)
.然后使用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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.