如何在子查询WHERE子句中重用变量?

时间:2019-03-26 19:08:22

标签: mysql

我有一张表,列出了每个用户的平均结果。 我想找到平均结果更好的用户百分比。

如果您是20位用户中的第五位用户,则20%的用户平均结果会更好。

average_results 
+---------+----------------+
| user_id | average_result |
+---------+----------------+
|       1 | 1.0000         |
|       3 | 0.3333         |
+---------+----------------+

这是我正在使用的查询。 当我使用@user_result0.3333进行硬编码时,它可以工作,但是当我不使用positionposition2

时,它却不能工作。
SELECT @user_result, position, position2, total, position/total 
FROM 
(
   SELECT @user_result := average_result 
   FROM average_results 
   WHERE user_id = 3  
) as T0,
(
   SELECT COUNT(average_result) as position  
   FROM average_results
   where average_result > @user_result
) AS T1,
(
   SELECT COUNT(average_result) as position2
   FROM average_results
   where average_result > 0.3333
) AS T12,
(
   SELECT COUNT(average_result) as total  
   FROM average_results
) AS T2
Expected output

+--------------+----------+-----------+-------+----------------+
| @user_result | position | position2 | total | position/total |
+--------------+----------+-----------+-------+----------------+
| 0.3333       |        1 |         1 |     2 | 0.5000         |
+--------------+----------+-----------+-------+----------------+

Actual output

+--------------+----------+-----------+-------+----------------+
| @user_result | position | position2 | total | position/total |
+--------------+----------+-----------+-------+----------------+
| 0.3333       |        0 |         1 |     2 | 0.0000         |
+--------------+----------+-----------+-------+----------------+

2 个答案:

答案 0 :(得分:0)

我建议使用类似以下的内容,它不能回答您关于变量的实际问题,但是我想您想要的。

SELECT t.*, position/total
FROM
(
 SELECT 
  ar2.average_result as user_result,
  SUM(CASE WHEN ar1.average_result > ar2.average_result THEN 1 ELSE 0 END) as position,
  COUNT(*) as total
 FROM average_results ar1 INNER JOIN average_results ar2
  ON ar2.user_id = 3
) t

这里是sqlfiddle of it working

答案 1 :(得分:0)

尝试一下:

SELECT *, position / total as 'position / result' 
FROM (
    SELECT 
          MAX( IF(user_id = 3 , average_result, null ) ) as result
        , COUNT(IF( average_result >
            (SELECT  MAX( IF(user_id = 3 , average_result, null ) )
            FROM average_results ), 1,NULL)) as position
        , COUNT( IF( average_result > 0.3333 , 1 , NULL) ) as position2
        , COUNT(average_result) as total
    FROM average_results
    ) as tmp;

样本