-2

我有这个问题,我已经苦苦挣扎了几个小时,似乎找不到解决方案来解决它并得到正确的答案。

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;

在第一个语句中,我使用 max 和 min 函数来查找员工的费率(如果已更改)之间的差异。

不使用 where 语句的结果,

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

我想在 select 语句中使用 max-min 的结果来只给我更改费率的员工的结果,例如:David Bradley 13.50?

4

1 回答 1

0

不,你不想。你想要的是一个子句。这用于过滤聚合值:

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;

是一个 db<>fiddle,表明它适用于 MySQL。

或者,您可以使用表达式:

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

请注意查询的其他更改:

  • 使用表别名。这使查询更易于编写和阅读。
  • 表别名是表名的缩写,因此它们是有意义的。
  • 没有select distinctselect distinct几乎从不适合group by,因为group by已经返回不同的行。
  • having在 MySQL 中,您可以在子句中使用列别名;它们不能用于where.
于 2019-10-14T16:53:47.050 回答