这是订单表信息
+----+----------+------------+------+
| id | username | goods_name | num |
+----+----------+------------+------+
| 1 | Tom | A | 3 |
| 2 | Rose | C | 1 |
| 3 | Rose | B | 5 |
| 4 | Tom | A | 1 |
+----+----------+------------+------+
现在想找出购买两款以上产品的用户,请问SQL怎么写
各位亲们看清题目啊,是购买两款以上产品的用户,表里面Tom购买了两次,单他都购买的A产品,所有不能被查询出来的,只有Rose,他购买了C和B产品,所以他可以被查询出来
If the goods_name is different, it means they are different products. Buying more than 2 models has nothing to do with buying a product whose num is more than 2.
None of the answers above are correct.
select username, count(*) as cnt from t_tablename group by username, goods_name having cnt > 2;
select count(username) as number having number >=2
Written while lying on the bed, that’s what it means.
Sorry, I didn’t read your question carefully last time, and I didn’t use my brain to give you an idea. This personal test is feasible, I wish the author good luck in his work.
假设表名是record, select count(*) as name_count, sub.username from (select username, goods_name from record group by username, goods_name) as sub group by sub.username where sub.namecount > 2
要count(distinct good_name)
The first one: select username,count(t.goods_name) as nums from (select DISTINCT(goods_name),username from shop) as t group by t.username having nums>1;
Improved answer:
select username,count(DISTINCT(goods_name)) as nums from shop group by username having nums>1;
Also in my additional comment
select username, count(*) as cnt from (select username from t group by username,goods_name) as a group by a.username having cnt > 2;