我遇到了创建组排名的MySQL If语句的问题。这是MySQL声明:
SELECT EnCode, EnName, QuScore,
@scorerank := IF(@currathlete = EnCode, @scorerank + 1, 1),
@currathlete := EnCode
FROM ranking ORDER BY EnCode, QuScore DESC
目前提供以下输出
'1004277','Ashe','1628','1','1004277'
'1004277','Ashe','1309','1','1004277'
'1004277','Ashe','1263','1','1004277'
'1004277','Ashe','648','1','1004277'
'1004277','Ashe','645','1','1004277'
'1004277','Ashe','1628','1','1004277'
'1015934', 'Sabina', '544', '1', '1015934'
'1015934', 'Sabina', '455', '1', '1015934'
'1015934', 'Sabina', '276', '1', '1015934'
'1015934', 'Sabina', '216', '1', '1015934'
它应该做的是增加每个' 1'具有相同代码的每一行的数字为1,然后当它看到不同的代码编号时再从1开始(1004277,在这种情况下为1015934)
任何帮助都表示赞赏,因为我已经使用上述方法在线跟踪了一些示例,但似乎在这一点上遇到了同样的问题。
答案 0 :(得分:1)
你必须初始化你的变量,否则它们是null
(至少在会话开始时,如果你运行它两次可能不再这样),你的查询将给出奇怪的结果。尝试
SELECT EnCode, EnName, QuScore,
@scorerank := IF(@currathlete = EnCode, @scorerank + 1, 1),
@currathlete := EnCode
FROM ranking, (select @currathlete := '', @scorerank := 0) init
ORDER BY EnCode, QuScore DESC
答案 1 :(得分:1)
在存储过程中尝试这种方式:
drop PROCEDURE if EXISTS INCREMENTME;
create PROCEDURE INCREMENTME()
BEGIN
DECLARE OldEnNamevar VARCHAR(10) DEFAULT NULL;
DECLARE done INT DEFAULT FALSE;
DECLARE Encodevar VARCHAR(10);
DECLARE EnNamevar VARCHAR(10);
DECLARE QuScorevar VARCHAR(10);
DECLARE scorerankvar VARCHAR(10);
DECLARE currathalthletevar VARCHAR(10);
DECLARE countcode int(29) DEFAULT(1);
DECLARE counter int(20) default 0;
DECLARE get_cur CURSOR FOR select `Encode`,`EnName`,`QuScore`,`scorerank`,`currathalthlete` from tbl_ranking;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;
drop table if exists temp_temptable;
create TEMPORARY table temp_temptable(Encodevar VARCHAR(50) NULL,EnNamevar VARCHAR(50) NULL,QuScorevar VARCHAR(50) NULL,scorerankvar VARCHAR(50) NULL,currathalthletevar VARCHAR(50) NULL,recordCount int(10) null);
OPEN get_cur;
REPEAT
set counter = counter + 1;
FETCH get_cur INTO Encodevar,EnNamevar,QuScorevar,scorerankvar,currathalthletevar;
if (OldEnNamevar = EnNamevar) THEN
set countcode = countcode +1;
ELSE
if(counter=1) then
set countcode = 1;
ELSE
set countcode = 0;
end if;
end if;
if (OldEnNamevar != EnNamevar) THEN
set countcode = 1;
end if;
if(OldEnNamevar=NULL) then
set countcode = 1;
end if;
insert into temp_temptable (Encodevar,EnNamevar,QuScorevar,scorerankvar,currathalthletevar,recordCount) values(Encodevar,EnNamevar,QuScorevar,scorerankvar,currathalthletevar,countcode);
set OldEnNamevar = EnNamevar;
UNTIL done END REPEAT;
select * from temp_temptable;
drop temporary table if exists temp_temptable;
CLOSE get_cur;
END
调用这样的程序: 致电INCREMENTME();