遇到一个问题 :
题目:
=========================
用户名 商品 数量
A 甲 1
B 乙 2
C 丙 2
B 甲 1
A 丙 2
C 丙 1
写sql语句
要求查出 购买商品两种类型以上(含)的用户集合
数据表中的数据如下:
一:
id name goodsname num
1 A JI 1
2 B JK 2
3 C J 3
4 B JKL 4
5 A JKLM 5
6 C J 6
同事们给出的意见是:
- SELECT temp.name
- FROM (
- SELECT count(tempone.goodsname) as nums,
- tempone.name
- FROM tempone
- GROUP BY tempone.name
- ) temp
- WHERE temp.nums > 1
SELECT temp.name FROM ( SELECT count(tempone.goodsname) as nums, tempone.name FROM tempone GROUP BY tempone.name ) temp WHERE temp.nums > 1
查出来的结构如下
二
name
A
B
C
C用户是只卖了一种商品 应该被排除... (这里需要考虑去重)
如是参考了些列文档...http://sql.1keydata.com/cn/sql-count.php
把count函数和distinct函数组合起来的用法
- SELECT temp.name
- FROM (
- SELECT count(DISTINCT tempone.goodsname) as nums,
- tempone.name
- FROM tempone
- GROUP BY tempone.name
- ) temp
- WHERE temp.nums > 1
SELECT temp.name FROM ( SELECT count(DISTINCT tempone.goodsname) as nums, tempone.name FROM tempone GROUP BY tempone.name ) temp WHERE temp.nums > 1
查出来的结构如下
三
name
A
还有一种查询方式是
select temp.name
from temp
group by temp.name
having COUNT(distinct goodsname) > 1
也可以达到相同的效果
主要总结count 与 distinct的联合使用
===
总结才是记住东西的根本