如何在mysql中使用聚合函数为变量赋值?

时间:2014-03-13 16:18:14

标签: mysql sql variables where

这是我的表结构和数据。

create table StudentInformation
(
    sId INT(5),
    name VARCHAR(50),
    sClass VARCHAR(10),
    maths INT(5),
    physics INT(5),
    chemistry INT(5)
);

INSERT INTO StudentInformation
values
(1, 'Jai', '11th', 60, 75, 65),
(2, 'Leela', '12th', 91, 87, 94),
(3, 'Suresh', '11th', 75, 68, 70),
(4, 'Ramesh', '11th', 50, 67, 55),
(5, 'Janki', '12th', 78, 89, 78),
(6, 'Lalu', '12th', 30, 38, 45),
(7, 'Amit', '11th', 91, 95, 93),
(8, 'Komal', '11th', 66, 78, 74),
(9, 'Sanjay', '12th', 25, 40, 35);

现在我想计算每个班级的平均分数 我试过这个问题:

SELECT
sClass class,
@var := sum(maths+physics+chemistry)/(count(sid)*3) as avgMarksPerSubject,
@var as variableValue,
count(sid) as numberOfStudents
FROM StudentInformation
#where @var > 65
group by sClass;

这里必须使用变量,因为这只是我实际任务的一个例子 现在我想拥有超过65分的记录 是否可以在WHERE子句中使用变量?
我没有在@var中获得实际数据,我如何在WHERE子句中使用它? 您可以尝试sql查询here 有什么建议吗? 感谢

1 个答案:

答案 0 :(得分:1)

只有在预初始化时,才能在where子句中使用用户定义的会话变量。除非另有说明,否则由于SQL-Query-Order-of-Operations,变量将具有默认值NULL,并且条件可能无法满足预期的结果。

set @var:=0;

SELECT
      sClass class,
      @var := cast(sum(maths+physics+chemistry)
                   /(count(sid)*3) as decimal(6,2)
              ) as avgMarksPerSubject,
      @var as variableValue,
      count(sid) as numberOfStudents
FROM  StudentInformation
where @var < 65
group by sClass
;

+-------+--------------------+---------------+------------------+
| CLASS | AVGMARKSPERSUBJECT | VARIABLEVALUE | NUMBEROFSTUDENTS |
+-------+--------------------+---------------+------------------+
| 11th  |              72.13 |             0 |                5 |
| 12th  |              60.83 |             0 |                4 |
+-------+--------------------+---------------+------------------+

在这里,您可以清楚地看到变量未按行分配任何值,也不会从上一列表达式中计算的值中分配。

您可以通过运行以下查询来查看其副作用:

select * from (
  SELECT
      sClass class,
      @var := cast(sum(maths+physics+chemistry)
                   /(count(sid)*3) as decimal(6,2)
              ) as avgMarksPerSubject,
      @var as variableValue,
      count(sid) as numberOfStudents
  FROM StudentInformation
  group by sClass
) r where avgMarksPerSubject > 65

+-------+--------------------+---------------+------------------+
| CLASS | AVGMARKSPERSUBJECT | VARIABLEVALUE | NUMBEROFSTUDENTS |
+-------+--------------------+---------------+------------------+
| 11th  |              72.13 |         60.83 |                5 |
+-------+--------------------+---------------+------------------+

示例 @ SQL Fiddle