仅在确定的行上使用agregate函数

时间:2017-11-12 13:46:03

标签: mysql

当我选择确定的IT工作者的薪水时,我必须只使用聚合函数(所以不检查列中的确切值,确定行)。 它不像SELECT SUM(salary) FROM table WHERE occupation='IT worker' LIMIT <here stays which place the person has on the list>, 1那么简单,是吗?我认为通过使用SUM命令,我们不会检查确切的值。

如果这个问题不可理解,我可以翻译整个练习。

编辑:练习 仅使用agregate函数(不检查列中的确切值,确定行)创建查询,这可以让我们了解确定的IT工作者的工资。 table包含: id int occupation varchar(50) salary int

2 个答案:

答案 0 :(得分:0)

我不会写查询,这是为了让你开始:

该表似乎有3个字段:id,职业和薪水。 每一行似乎都对应一个特定的工作人员

然后你可以使用agregate函数来计算不同职业的东西(例如)。

使用agregate函数的查询结构如下:

Select <fields and agregate functions>  
from table  
where <filter records to consider for the query before aggregation>  
group by <field having the same value, hence that can be grouped by>  
having <optional condition evaluated after doing the aggregation>

agregate函数的示例是Sum,Count,Avg。

问题不明确,但您可以使用信息来计算:

具有相同职业的工人数量 平均工资 按职业划分的总薪资收入。

答案 1 :(得分:0)

如果我们现在忽略部门,你可以做这样的事情

MariaDB [sandbox]> select emp_no, salary from employees ;
+--------+--------+
| emp_no | salary |
+--------+--------+
|      1 |  20000 |
|      2 |  39500 |
|      3 |  50000 |
|      4 |  19500 |
|      5 |  10000 |
|      6 |  19500 |
|      7 |  40000 |
|      9 |   NULL |
+--------+--------+
8 rows in set (0.00 sec)

MariaDB [sandbox]>  select emp_no,salary,
    ->  concat(rank,' of ' ,obs) as Rank,
    ->  Position,
    ->  reltoavg realtivetoavg
    ->   from
    ->  (
    ->  select emp_no,salary ,
    ->  @rn:=@rn+1 as Rank,
    ->  (select count(*) from employees) as obs,
    ->  concat('There are ',
    ->  (Select count(*) from employees e1 where e1.SALARY > e.salary) , ' employees who earn more and ',
    ->  (Select count(*) from employees e1 where e1.SALARY < e.salary and salary is not null) ,  ' who earn less') Position,
    ->  (select avg(salary) from employees) avgsalary,
    ->  if (salary > (select avg(salary) from employees), 'Salary is above average', 'salary is below average') reltoavg
    ->  from employees e,(Select @rn:=0) r
    ->  where salary is not null
    ->  order by salary
    ->  ) s
    ->  where s.emp_no = 1
    ->  ;
+--------+--------+--------+---------------------------------------------------------+-------------------------+
| emp_no | salary | Rank   | Position                                                | realtivetoavg           |
+--------+--------+--------+---------------------------------------------------------+-------------------------+
|      1 |  20000 | 4 of 8 | There are 3 employees who earn more and 3 who earn less | salary is below average |
+--------+--------+--------+---------------------------------------------------------+-------------------------+
1 row in set (0.00 sec)