从上面的图片中我有 n 的记录数 cat_id 和 sub_cat_id ,但在图片中只有两个记录。
所以我希望将最后和 secondlast score_in_per
值命名为lastScore
和latetsScore
..
我该如何检索..?
SELECT
(SELECT score_in_per FROM tbl_student_skill_score ORDER BY date DESC LIMIT 2,0) as lastScore,
(SELECT score_in_per FROM tbl_student_skill_score ORDER BY date DESC LIMIT 1) as latetsScore
我是这个复杂的mysql逻辑的新手。这就是我试过的..
示例:
假设一个用户电子邮件inststudent@yopmail.com
采用相同的测试2
次,测试与一个类别和子类别相关联。
所以用户将多次参加测试......
从那些记录我想得到最后两个记录的百分比。
答案 0 :(得分:1)
如果我理解正确的话;您想要选择特定学生所进行的特定类型考试的两个最新结果。
您没有正确使用LIMIT
子句。这是正确的语法:LIMIT {[offset,] row_count | row_count OFFSET offset}
。另外,你完全忽略了where子句。
所以查询应该是:
SELECT
(SELECT score_in_per FROM tbl_student_skill_score
WHERE user_email = "email of the user you are interested in"
AND cat_id = categoryOfTestOfInterest
AND sub_cat_id = subcategoryOfTestOfInterest
ORDER BY date DESC LIMIT 1, 1
)AS lastScore,
(SELECT score_in_per FROM tbl_student_skill_score
WHERE user_email = "email of the user you are interested in"
AND cat_id = categoryOfTestOfInterest
AND sub_cat_id = subcategoryOfTestOfInterest
ORDER BY date DESC LIMIT 1
)AS latetsScore;
如果一个学生每天可以多次参加考试(如你的形象所示),那么你也应该通过id订购(假设id对于较新的结果总是更大)或更好,只有id:
SELECT
(SELECT score_in_per FROM tbl_student_skill_score
WHERE user_email = "email of the user you are interested in"
AND cat_id = categoryOfTestOfInterest
AND sub_cat_id = subcategoryOfTestOfInterest
ORDER BY id DESC LIMIT 1, 1
)AS lastScore,
(SELECT score_in_per FROM tbl_student_skill_score
WHERE user_email = "email of the user you are interested in"
AND cat_id = categoryOfTestOfInterest
AND sub_cat_id = subcategoryOfTestOfInterest
ORDER BY id DESC LIMIT 1
)AS latetsScore;
答案 1 :(得分:1)
解决此问题的方法之一是使用分区依据
Step1:我按照分区的顺序按日期降序排列了不同cat_id和sub_cat_id的数据。
Step2:我使用了rank1这是最新的得分,并将其与rank2合并,这是第二个最后得分
with chck as
(select
cat_id,sub_cat_id,score_in_per,date1,
row_number() over(partition by cat_id,sub_cat_id order by
cat_id,sub_cat_id,date1 desc) as row_num
from tbl)
select a.*,b.second_last_score from
(select cat_id,sub_cat_id,score_in_per,date1,row_num as last_score from chck where row_num=1) a
left join
(select cat_id,sub_cat_id,score_in_per,date1,row_num as second_last_score from chck where row_num=2) b
on a.cat_id = b.cat_id and a.sub_cat_id = b.sub_cat_id;
如有任何疑问,请与我们联系。
答案 2 :(得分:0)
SELECT
( SELECT score_in_per FROM tbl_student_skill_score WHERE cat_id=1 and sub_cat_id=5 ORDER BY date,id DESC LIMIT 1 ) AS latestScore,
( SELECT score_in_per FROM tbl_student_skill_score WHERE cat_id=1 and sub_cat_id=5 ORDER BY date,id DESC LIMIT 1,1 ) AS lastScore