简体   繁体   中英

Can you use the result of a select statement in the where clause?

I have this question that I have been struggling with for a couple of hours and can't seem to find a solution to fix it and get the correct answer.

select distinct Person.Person.FirstName, Person.Person.LastName, MAX(HumanResources.EmployeePayHistory.Rate) - MIN(HumanResources.EmployeePayHistory.Rate) AS 'Difference'   
from Person.Person
inner join HumanResources.EmployeePayHistory on HumanResources.EmployeePayHistory.BusinessEntityID=Person.BusinessEntityID
where 
group by Person.FirstName, Person.LastName;

In the first statement, I use the max and min functions to find the difference between an employee's rate if it had been changed.

The results without using a where statement,

Syed    Abbas       0.00,
Kim Abercrombie     0.00,
Hazem   Abolrous    0.00,
Pilar   Ackerman    0.00,
Jay     Adams       0.00,
David   Bradley     13.50,
Alan    Brewer      0.00,
Eric    Brown       0.00,
Jo      Brown       0.00

I want to use the result from the max-min in the select statement to only give me the results of the employees who's rate was changed ex: David Bradley 13.50?

No. You don't want to. What you want is a having clause. This is use for filtering aggregation values:

select p.FirstName, p.LastName,
       (max(eph.Rate) - min(eph.Rate)) as difference   
from Person.Person p join
     HumanResources.EmployeePayHistory eph
     on eph.BusinessEntityID = p.BusinessEntityID
group by p.FirstName, p.LastName
having difference > 0;

Here is a db<>fiddle showing that it works for MySQL.

Alternatively, you can use an expression:

having max(eph.Rate) > min(eph.Rate)

Note other changes to the query:

  • Table aliases are used. This makes the query easier to write and to read.
  • The table aliases are abbreviations for the table name, so they are meaningful.
  • No select distinct . select distinct is almost never appropriate with group by , because group by already returns distinct rows.
  • In MySQL, you can use column aliases in the having clause; they cannot be used in the where .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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