我正在尝试构建一个没有成功的SQL查询。因为我是新手,我希望能找到你的帮助。
风景:商店正在为其客户组织奖励。这是他们拥有的数据库:
__________________________________________________________________
id | name | date | time | item | section |
__________________________________________________________________
01 | J. Smith | 2011-10-30 | 10:12:56 | shoes | sport |
02 | J. Smith | 2011-10-27 | 11:14:19 | T-shirt | sport |
03 | M. Douglas | 2011-11-01 | 04:00:42 | keyboard | computer |
04 | R. Obrian | 2010-12-31 | 11:33:57 | webcam | computer |
05 | M. Douglas | 2011-01-07 | 12:42:00 | webcam | computer |
06 | J. Smith | 2011-02-05 | 02:30:51 | T-shirt | sport |
07 | J. Smith | 2011-05-12 | 06:55:14 | bike | sport |
08 | J. Smith | 2011-03-15 | 09:59:22 | shoes | sport |
09 | J. Smith | 2011-09-09 | 08:10:36 | webcam | computer |
10 | J. Smith | 2011-06-09 | 10:00:38 |microphone| computer |
我希望为每个部分制作前10名客户列表,其中包括以下标准:最佳买家是谁购买了大量不同的商品。如果客户中的结果相同(购买的商品数量相同),最好的买家是第1次(日期和时间)购买所有商品。
例如,我希望得到以下十大结果表:
SPORT
____________________________________________________________
| name | items bought (different) | Date & Time |
____________________________________________________________
| XXXYYY | 16 | 2011-10-05 @07:15|
| ZZZZTT | 16 | 2011-10-05 @08:10|
| QQHAIJ | 16 | 2011-10-06 @10:35|
| TTTSFT | 15 | 2011-11-03 @12:22|
| LIUREN | 14 | 2011-11-14 @16:10|
| ODIRNU | 9 | 2011-07-03 @14:18|
| OIXUED | 8 | 2011-11-20 @03:03|
| SUHDKO | 7 | 2011-02-02 @22:51|
| TNODJH | 7 | 2011-06-10 @12:55|
| ENOSJR | 6 | 2011-04-04 @11:39|
_____________________________________________________________
每个部分的查询必须不同,我必须为SPORT,COMPUTER等等提供不同的字符串(和结果表)。
谁能帮帮我?提前谢谢!
鲍勃。
答案 0 :(得分:1)
这有用吗?
SELECT
t1.name,
COUNT(*) as `Distinct items bought`,
MIN(t1.computedDateTime) as `Date And Time`
FROM
(
SELECT
name, MIN(ADDTIME(date, time)) as computedDateTime, item
FROM
tablename
WHERE
Section = "sport"
GROUP BY
name, item
) t1
GROUP BY
name
ORDER BY
count(*), MIN(computedDateTime) DESC
LIMIT 10
内部选择(应该)生成由个人购买的不同项目的表格,仅限于"sport"
部分。然后外部选择按名称标识这些不同购买的总数,并对它们进行排序。
我现在没有立即测试,所以请谨慎使用。我最关心的是结合日期和时间的ADDTIME
功能,我以前没用过。
答案 1 :(得分:1)
SELECT name,
COUNT(DISTINCT item) AS items,
MIN(ADDTIME(`date`,`time`)) AS `datetime`
FROM purchase
WHERE section = 'computer'
GROUP BY name
ORDER BY items DESC, `datetime` ASC
LIMIT 0,10
示例表结果:
|- name -|- items -|- datetime -|
|- M. Douglas -|- 2 -|- 2011-01-07 12:42:00 -|
|- J. Smith -|- 2 -|- 2011-06-09 10:00:38 -|
|- R. Obrian -|- 1 -|- 2010-12-31 11:33:57 -|
SELECT name,
COUNT(DISTINCT item) AS items,
MAX(ADDTIME(`date`,`time`)) AS `datetime`
FROM purchase
WHERE section = 'computer'
GROUP BY name
ORDER BY items DESC, `datetime` ASC
LIMIT 0,10
示例表结果:
|- name -|- items -|- datetime -|
|- J. Smith -|- 2 -|- 2011-09-09 08:10:36 -|
|- M. Douglas -|- 2 -|- 2011-11-01 04:00:42 -|
|- R. Obrian -|- 1 -|- 2010-12-31 11:33:57 -|
答案 2 :(得分:0)
试试这个:
SELECT name, date, time, COUNT(DISTINCT item) AS NumOfItems
FROM Purchased
WHERE section = 'sport'
ORDER BY NumOfItems, date, time
LIMIT 10