需要LIMIT的子查询帮助

时间:2015-09-06 19:00:26

标签: mysql subquery

我需要用户id = x的每个标准ID的最后三个得分和总计。一旦我得到了这个,我就会找出每个分数/总分的百分比。然后我做一个平均百分比,这个百分比是该标准id的最终百分比。我遇到的问题是尝试输出每个标准ID的最终百分比。我能够做一个,但不知道如何构造查询来执行其余的行。

获取单个标准ID的结果

g++ -Iuser/include/plc-1.7 -c test.cpp 

这有效,

我尝试尝试相同的但是尝试使用多种标准ID。

SELECT sto_standard_id, avg((sto_count / sto_total) * 100)
FROM (
SELECT so.sto_standard_id,so.sto_count ,so.sto_total  
FROM mydb.sto_stat_overall as so 
WHERE sto_user_id = 1 
AND so.sto_standard_id = 4
ORDER BY sto_id 
DESC LIMIT 3) as sub

它仍然只返回一行。

以下是一些可以使用的数据。

SELECT sto_standard_id, avg((sto_count / sto_total) * 100)
FROM (
SELECT so.sto_standard_id,so.sto_count ,so.sto_total  
FROM mydb.sto_stat_overall as so 
WHERE so.sto_standard_id IN (SELECT DISTINCT sto_standard_id FROM mydb.sto_stat_overall WHERE sto_user_id = 1)
ORDER BY sto_id 
DESC LIMIT 3) as sub

1 个答案:

答案 0 :(得分:1)

select sto_standard_id, avg((sto_count / sto_total) * 100) from (
select @rank:=if(@prev_cat=sto_standard_id ,@rank+1,1) as rank
  ,so.sto_standard_id,so.sto_count ,so.sto_total,
  @prev_cat:=sto_standard_id 

from sto_stat_overall so,(select @rank:=0, @prev_cat:="")t
  WHERE sto_user_id = 1
order by sto_standard_id , sto_id  desc
  ) temp
  where temp.rank<=3
  group by sto_standard_id