查询需要计算每个用户的总积分。对于每个qid,具有较低时间的用户获得一个点,并且总点数是所有点的总和。下面的查询只返回每个用户的总尝试次数,需要一种方法来返回点。
Incorrect Query=select user, count(*) from (select * from (select * from xyz order by
time ASC) as temp1 group by temp1.user,temp1.qid) AS temp2 group by user
DB:
CREATE TABLE xyz (
id INT PRIMARY KEY AUTO_INCREMENT,
user VARCHAR(20),
time INT,
qid INT
);
INSERT INTO xyz VALUES ( 1 , 'abc' , 15 , 1);
INSERT INTO xyz VALUES ( 2 , 'abc' , 6 , 1);
INSERT INTO xyz VALUES ( 3 , 'xyz' , 11 , 1);
INSERT INTO xyz VALUES ( 4 , 'abc' , 4 , 1);
INSERT INTO xyz VALUES ( 5 , 'xyz' , 13 , 2);
INSERT INTO xyz VALUES ( 6 , 'abc' , 11 ,2);
INSERT INTO xyz VALUES ( 7 , 'abc' , 9 , 3);
INSERT INTO xyz VALUES ( 8 , 'xyz' , 10 , 3);
INSERT INTO xyz VALUES ( 9 , 'xyz' , 2 , 3);
INSERT INTO xyz VALUES ( 10 , 'xyz' , 2 , 4);
预期产出:
USER Score
abc 2
xyz 2
输出说明:
For qid=1, abc has lower time so 1 point to abc
For qid=2, abc has lower time so 1 point to abc
For qid=3, xyz has lower time so 1 point to xyz
For qid=4, xyz has lower time so 1 point to xyz
由于
答案 0 :(得分:3)
您需要找到每个qid
用户“第一”的次数。这是一种方法:
select xyz.user, count(*) as score
from xyz join
(select qid, min(time) as mintime
from xyz
group by qid
) q
on xyz.qid = q.qid and xyz.time = q.mintime
group by xyz.user;