简体   繁体   English

我想知道我是否可以在另一个关键字中使用 SQL 关键字,例如 COUNT(DISTINCT(<columnname> ))</columnname>

[英]I want to know if i can use an SQL keyword inside another keyword , like COUNT(DISTINCT(<columnname>))

SELECT AVG(salary) FROM emp where COUNT(DISTINCT(dept)) > 3 ;

Using this query, i want to calculate the average salary of Departments where employee number is more than 3.使用此查询,我想计算员工人数超过 3 的部门的平均工资。

You can use HAVING:您可以使用 HAVING:

SELECT AVG(salary) 
FROM emp 
HAVING COUNT(DISTINCT dept) > 3 ;

I am not sure what is it exactly you need but here is a demo of my example and one more example with a function inside a function DEMO我不确定您到底需要什么,但这是我的示例的演示,以及 function 演示中的 function 的另一个示例

Above is answer for Oracle.以上是 Oracle 的答案。 For sqlserver I suggest to use "function inside of function" like this:对于 sqlserver,我建议使用“函数内部的函数”,如下所示:

select avg(tolumn1)
from (select count(salary) as tolumn1
      from emp) A

i want to calculate the average salary of Departments where employee number is more than 3.我想计算员工人数超过 3 的部门的平均工资。

As I interpret the question, you want:当我解释这个问题时,你想要:

select dept, avg(salary)
from emp
group by dept
having count(*) > 3;

If you want the average across all departments, then it is not clear if you want the average of the department averages.如果你想要所有部门的平均值,那么你是否想要部门平均值的平均值就不清楚了。 Or the average of the employees in those departments.或者这些部门员工的平均值。 Either way, you need a subquery:无论哪种方式,您都需要一个子查询:

select avg(dept_avg) as average_of_department_salaries,
       sum(sum_salary) / sum(num_emp) as employee_average_salary
from (select dept, avg(salary) as dept_avg, count(*) as num_emp, sum(salary) as sum_salary
      from emp
      group by dept
      having count(*) > 3
     ) d

Select Avg(E.Salary),D.Department_name from Departments AS D inner join Employee AS E on D.Dept_Id = E.Dept_Id group by Department_name having count(Emp_Id)>3

The required result for the problem cannot be obtained without a join on Department table and the Employee table.如果没有对 Department 表和 Employee 表进行连接,则无法获得问题所需的结果。 Hence using alias for the two tables with a Group by clause followed by Having clause.因此,使用 Group by 子句后跟 Have 子句的两个表使用别名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM