如何在MySql中编写此查询?

时间:2015-04-29 14:23:16

标签: mysql

我有一张桌子:

    question_id | user_id | answer | weight
        213     |   22    |   25   |   50
        213     |   106   |   75   |   50
        216     |   22    |   100  |   50
        216     |   106   |   0    |   50    

我想编写一个MySql查询,为两个指定的user_id计算:

user1's weight * (user1's answer - user2's answer)

并将所有question_id的值相加。因此,对于上面的示例,如果user1的id为22且user2的id为106,则为

50*(25-75)+50*(100-0)=2500

2 个答案:

答案 0 :(得分:1)

您可以使用自我加入来执行此操作:

SELECT SUM(u1.weight * (u1.answer - u2.answer)) AS total
FROM table u1
JOIN table u2 ON u2.question_id = u1.question_id
WHERE u1.user_id = 22 AND u2.user_id = 106

确保列类型不是“无符号”,否则,您需要将值转换为已签名。

答案 1 :(得分:0)

我开始写一个案例陈述,让每个球员得分和每个问题的重量如下:

SELECT
  question_id,
  MAX(CASE WHEN user_id = 22 THEN answer ELSE null END) AS user1Score,
  MAX(CASE WHEN user_id = 22 THEN weight ELSE null END) AS user1Weight,
  MAX(CASE WHEN user_id = 106 THEN answer ELSE null END) AS user2Score,
  MAX(CASE WHEN user_id = 106 THEN weight ELSE null END) AS user2Weight
FROM myTable
GROUP BY question_id;

我必须添加MAX()的原因是因为没有它我会得到两行,一行用于user1,其中user2' s值为null,另一行用于相反的行。这有助于将每个问题组合成一行。

一旦我得到了这些结果,我就用它作为子查询来预先形成你想要的计算:

SELECT SUM(user1Weight * (user1Score - user2Score)) AS total
FROM(
  SELECT
    question_id,
    MAX(CASE WHEN user_id = 22 THEN answer ELSE null END) AS user1Score,
    MAX(CASE WHEN user_id = 22 THEN weight ELSE null END) AS user1Weight,
    MAX(CASE WHEN user_id = 106 THEN answer ELSE null END) AS user2Score,
    MAX(CASE WHEN user_id = 106 THEN weight ELSE null END) AS user2Weight
  FROM myTable
  GROUP BY question_id) tmp;

以下是SQL Fiddle示例。