日期:2014-05-19  浏览次数:20405 次

请问这个sql语句怎么写?
有个购物表order,字段有id,username,product,pro_num(产品数量)。要求写一条语句只显示出所有购物超过3次的用户,

不知道是不是很简单,但我还真不知道,希望高手帮忙。

------解决方案--------------------
这个order表设计的好像有点问题,因为这个表设计的有问题,所以在这个表上,无法实现你想要的功能。解决方法是,另外设计数据表。

你需要设计两个表:

orders
===========
ordernum
userID
orderdate
custemail
subtotal
salestax
shipping
total


orderItems
===============
ordernum
productid
name
price
quantity
total

注意到:两个表具有同样的一个表段:ordernum。通过这个表段,实现两个表的关系。

一个订单(order)内,可以有多个货物(orderItem)。所以它们需要独立开成两个表。
设计好这两个表后,回到你的问题来。

为了方便描述和理解,我把orders表简化成下面这个表。

id userID
==============
1 tom
2 tom
3 tom
4 Niky
5 Niky
6 sam
7 sam
8 sam
9 sam

依照你的想法,通过观察,执行的结果应该是
tom
sam

看看如何实现?
首先,用一个GROUP BY对这组数据进行分组
SELECT userID,count(*) AS BuyTimes FROM [order] GROUP BY userID
得到这个表ResultTable

userID BuyTimes
=============
Niky 2
sam 4
tom 3

在这个表的基础上,在进行查询
SELECT * FROM ResultTable WHERE BuyTimes > =3
这就可以得到购买超过3次的用户了

userid consumeTime
=================
sam 4
tom 3


你可以把这两个操作并成一个语句,方法是使用SELECT 子查询(subquery)。
SELECT * FROM
(
SELECT userID,count(*) AS BuyTimes FROM [order] GROUP BY userID
)
WHERE BuyTimes > =3

------解决方案--------------------
容易啊 select top 3 * from [order] where pro_num> 3
------解决方案--------------------

楼上的看清楚了哦
pro_num是产品数量.不是购物次数..........
------解决方案--------------------
id是购物id还是用户id?

如果是购物id,那么username就不能同名了


如果是用户id的话
select distinct id from order group by id where count(id) > 3

如果是购物id
select distinct username from order group by username where count(username) > 3
------解决方案--------------------
不管ID是什么
用select distinct username from order group by username where count(username) > 3
都可以吧
------解决方案--------------------
select username from order group by username having count(username )> =3
------解决方案--------------------
select * from order group by username where count(username)> =3