问题:找到每个类别中至少有 10 个项目的前 2 个用户。
表结构:
CREATE TABLE items(
id INT AUTO_INCREMENT PRIMARY KEY,
datetime datetime,
category INT,
user INT,
items_count INT
);
样本数据:
INSERT INTO items (datetime, category, user, items_count) VALUES
('2013-01-01 00:00:00', 1, 1, 10),
('2013-01-01 00:00:01', 1, 2, 1),
('2013-01-01 00:00:02', 1, 3, 10),
('2013-01-01 00:00:03', 1, 2, 9),
('2013-01-01 00:00:00', 2, 4, 10),
('2013-01-01 00:00:01', 2, 1, 10),
('2013-01-01 00:00:01', 2, 5, 10);
期望的结果:
category user
1 1
1 3
2 4
2 5
注意:如结果所示,当多个用户同时满足要求时,我需要能够显示对用户的偏好。
SQL小提琴:
http://sqlfiddle.com/#!2/58e60
这是我尝试过的:
SELECT
Derived.*,
IF (@category != Derived.category, @rank := 1, @rank := @rank + 1) AS rank,
@category := category
FROM(
SELECT
category,
user,
SUM(items_count) AS items_count,
MAX(datetime) AS datetime
FROM items
GROUP BY
category,
user
HAVING
SUM(items_count) >= 10
) AS Derived
JOIN(SELECT @rank := 0, @category := 0) AS r
HAVING
rank <= 2
ORDER BY
Derived.category,
Derived.datetime
但这是错误的。它不仅不考虑用户优先级,而且会使用如下数据产生错误的结果:
('2013-01-01 00:00:00', 1, 1, 10),
('2013-01-01 00:00:01', 1, 2, 1),
('2013-01-01 00:00:02', 1, 3, 10),
('2013-01-01 00:00:03', 1, 2, 9),
('2013-01-01 00:00:10', 1, 3, 1);
附加信息:我不知道程序是否可以在这种情况下有所作为,但不幸的是它也不是一个选项。运行此查询的用户只有 SELECT 权限。