我有一张表格,其中包含人员执行的操作列表。
在
SELECT COUNT(NICK) AS TOTAL, NICK, ACTION FROM ACTIONS2 GROUP BY ACTION,NICK ORDER BY NICK ASC, TOTAL DESC
它看起来像这样:
total nick action
13 0xlne destroyed
5 0xlne captured
5 0xlne deployed
1 13key destroyed
2 74pawel deployed
1 74pawel destroyed
1 74pawel captured
现在,我想多次动作破坏x75,捕获x500,部署x125等等,所以第一行应该看起来:(13 * 75 + 5 * 500 + 5 * 125 = 4100)
total nick
4100 0xlne
75 13key
等等。有没有办法将这几种类型的操作与值相关联而不创建新表,并在乘法和求和之前加入它们?
答案 0 :(得分:0)
这是使用CASE / WHEN
的问题SELECT
SUM(CASE WHEN action='destroyed' THEN total*75 WHEN action='captured' THEN total*500 ELSE total*125 END), nick
FROM (SELECT COUNT(NICK) AS TOTAL, NICK, ACTION FROM ACTIONS2 GROUP BY ACTION,NICK ORDER BY NICK ASC, TOTAL DESC) AS nicks
GROUP by nick;
作为脚注:通常大写用于SQL保留字,小写用于列/表名。
答案 1 :(得分:0)
使用条件聚合并对加权值求和:
SELECT NICK, COUNT(*) AS totalAction
COALESCE(SUM(ACTION='destroyed'),0)*75 +
COALESCE(SUM(ACTION='capture'),0)*500 +
COALESCE(SUM(ACTION='deploy'),0)*125
as totalPoints
FROM ACTIONS2
GROUP BY NICK
ORDER BY NICK ASC, totalAction DESC
表达式
COALESCE(SUM(ACTION='destroyed'),0)*75
也可以写成
COUNT(CASE WHEN ACTION='destroyed' THEN 1 END)*75
或者
COUNT(ACTION='destroyed' OR NULL)*75
或许多其他方式。
有点不同的方法:
SELECT NICK, COUNT(*) AS totalAction,
SUM(
CASE ACTION
WHEN 'destroyed' THEN 75
WHEN 'capture' THEN 500
WHEN 'deploy' THEN 125
ELSE 0
END
) as totalPoints
FROM ACTIONS2
GROUP BY NICK
ORDER BY NICK ASC, totalAction DESC