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

标签 mysql

我有一个表格,其中包含每个用户的平均结果。 我想找出平均结果更好的用户百分比。

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

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

这是我正在使用的查询。 当我用 0.3333@user_result 进行硬编码时,它可以工作,但是当我不这样做时,它就不起作用,正如您在 position位置2

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         |
+--------------+----------+-----------+-------+----------------+

最佳答案

我会建议如下内容,它不会回答您关于变量的实际问题,但我认为可以满足您的要求。

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 .

关于mysql - 如何在子查询 WHERE 子句中重用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55364626/

相关文章:

javascript - PHP - 检索与单选按钮对应的所有数据

mysql - 优化大型 MySQL 表 - 分区?

MySQL SELECT * WHERE 名称 = "something with a backslash\"

mysql - Magento 1.8.0在处理您的请求时出错

mysql - 如何将 Joomla 博客中的内容转移到 Blogger 或 Wordpress 中?

php - Laravel 4.2 ORM 查询

php - Android - 连接到 wamp = 服务器问候错误

mysql - 使用 Between 进行连接查询的限制

python - 属性错误 : 'tuple' object has no attribute 'encode' when inserting data using mysql-connector

php - 想要在一张表中将mysql中的两列设置为自动增量int