SQL Server引用嵌套子查询

时间:2012-02-12 20:42:39

标签: sql-server-2008 join subquery

在一个sql server数据库中,我试图通过奖金返回带有最多钱的疯狂。因此,我有一个子查询来计算每个性别的奖金总和,另一个子查询返回最大值,最后,我的主查询返回具有此最大值的性别。但是我的代码无效。

  

SELECT E.Gender,maxx.mm

   FROM HumanResources.Employee as E, 
   (SELECT MAX(Bonus) as mm 
    FROM (SELECT E.Gender, SUM(SP.Bonus) AS Bonus 
          FROM HumanResources.Employee AS E, Sales.SalesPerson AS SP
          GROUP BY E.Gender) 
     AS gen) AS  maxx
     

其中E.Gender = gen.Gender;

最后一行:其中E.Gender = gen.Gender似乎不能作为gen.Gender无法绑定

请帮助

2 个答案:

答案 0 :(得分:1)

我不是subquery(subquery(subquery(模型的忠实粉丝,因为它通常很浪费,通常难以解析/理解/重写。以下是我在看到它时最初想要重新编写的内容:

SELECT TOP (1) E.Gender, mm = SUM(SP.Bonus)
  FROM Sales.SalesPerson AS sp 
  INNER JOIN HumanResources.Employee AS E
  ON E.EmployeeID = sp.EmployeeID -- guess on relationship
GROUP BY E.Gender
ORDER BY mm DESC;

另一种方式(根据计划可能更有效率,因为您将从联接中消除除一名员工之外的所有员工 - 可能在上面发生的事情,但也可能没有):

;WITH sp AS
(
  SELECT TOP 1 EmployeeID, mm = SUM(Bonus)
    FROM Sales.SalesPerson
    GROUP BY EmployeeID
    ORDER BY mm DESC
)
SELECT E.Gender, topsp.mm
  FROM sp
  INNER JOIN HumanResources.Employee AS E
  ON E.EmployeeID = sp.EmployeeID; -- again guessing on relationship

答案 1 :(得分:1)

将过滤器放在子查询中。您可以从内部引用外部查询,因此:

 AS gen) AS  maxx

变为

 AS gen WHERE  E.Gender = gen.Gender) AS  maxx