我有下表:
row_number itemID score
1 45 99
2 45 47
1 46 98
2 46 20
1 47 98
2 47 20
… … …
以下查询的输出是什么:
SET @num := 0, @itemID_grouping := '';
SELECT row_number,
itemID,
score
FROM (SELECT itemID,
score,
@num := IF(@itemID_grouping = itemID, @num + 1, 1) AS row_number,
@itemID_grouping := itemID AS temp
FROM my_table
ORDER BY itemID,
score DESC) AS x
WHERE x.row_number <= 2;
来自以下原始表:
my_table:
itemID score
46 99
… …
因此,对于每个itemID
,我有一组两个值(两个最高分)。
我想要另一个包含&#39; y&#39;或者,如果对于每个集合,row_number=1
的数字大于某个阈值且row_number=2
的数字低于某个阈值。有什么想法吗?
答案 0 :(得分:0)
好的,我找到了一个答案(可能不是很快,但它可以完成工作):
set @num := 0, @itemID_grouping := '',@num_temp:=0,@flag1:=0,@flag2:=0;
select row_number,itemID, score,flag2
from
(
select itemID,score,
@num := if(@itemID_grouping = itemID, @num + 1, 1) as row_number,
@flag1:= if(@num=1 AND score>90,1,0) as flag1,
@flag2:= if(@num=2 AND @flag_temp=1 AND score<70,1,0) as flag2,
@itemID_grouping := itemID as temp,
@flag_temp:=@flag1 as temp_flag
from my_table
order by itemID,score desc
) as x
where x.row_number <= 2;