如何编写如下查询:
SELECT userid,
(IF field IN(1,2,3,900,658,4,5,6,9,10,11,12,13,10025,14,15,16,17,18,19) score = score +20, ELSE IF field IN(23,45,67,777,53,54) score = score + 40,
ELSE IF field IN(120,332,563,334,634,423,333) score = score + 60) AS score
WHERE field IN(1,2,3,900,658,4,5,6,9,10,11,12,13,10025,14,15,16,17,18,19,23,45,67,777,53,54,120,332,563,334,634,423,333)
GROUP BY userid ORDER BY score DESC
我试图找到将字段设置为给定数字之一的所有用户。某些数字有不同的分数(20分,40分和60分),所以我需要将分数相加得到每个用户ID的总分,然后按总分对用户进行排名。
答案 0 :(得分:1)
您可能正在寻找:
SELECT userid,
sum(
CASE
WHEN field IN (1,2,3,4,5,6,9,10,11,12,13,14,15,16,17,18,19) THEN 20
WHEN field IN (23,45,67,53,54) THEN 40
ELSE 60
END) AS score
FROM mytable
WHERE field IN (1,2,3,4,5,6,9,10,11,12,13,14,15,16,17,18,19,23,45,67,53,54,120,
332,563,334,634,423,333)
GROUP BY userid
ORDER BY score DESC
答案 1 :(得分:0)
你错过了桌子,你可以用案例
select UserId,
case
when field < 20 then Score + 20
when field IN(23,45,67,53,54) then Score + 40
else score + 60
end as Score
FROM mytable
where field IN(1,2,3,4,5,6,9,10,11,12,13,14,15,16,17,18,19,23,45,67,53,54,120,332,563,334,634,423,333)
group by UserId
order by Score desc