0

我试图让销售额最高的员工

Employee    DeptNo  Date        Sales
Chris       2       2012/1/1    1000
Joe         1       2012/1/1    900
Arthur      3       2012/1/1    1100
Chris       2       2012/3/1    1200
Joe         1       2012/2/1    1500
Arthur      3       2010/2/1    1200
Joe         1       2010/3/1    900
Arthur      3       2010/3/1    1100
Arthur      3       2010/4/1    1200
Joe         1       2012/4/1    1500
Chris       2       2010/4/1    1800

我尝试使用两个子查询,然后将它们一起比较以找到更高的值

SELECT c1.Employee,
       c1.TOTAL_SALES
FROM  (SELECT Employee,
              Sum(sales) AS TOTAL_SALES
       FROM   EmployeeSales
       GROUP  BY Employee) c1,
      (SELECT Employee,
              Sum(sales) AS TOTAL_SALES
       FROM   EmployeeSales
       GROUP  BY Employee) c2
WHERE  ( c1.TOTAL_SALES > c2.TOTAL_SALES
         AND c1.Employee > c2.Employee ) 

但是结果查询给了我两行

Employee    TOTAL_SALES
joe         4800
joe         4800

我究竟做错了什么?

4

5 回答 5

2

我会使用 CTE。

;With [CTE] as (
    Select
        [Employee]
        ,sum([Sales]) as [Total_Sales]
        ,Row_Number()
            Over(order by sum([sales]) Desc) as [RN]
    From [EmployeeSales]
    Group by [Employee]
)
Select
    [Employee]
    ,[Total_Sales]
From [CTE]
Where [RN] = 1

工作代码 SQL Fiddle 示例: http ://sqlfiddle.com/#!3/bd772/2

于 2012-07-11T13:09:48.080 回答
1

要返回总销售额最高的所有员工,可以使用 SQL Server 专有的 TOP WITH TIES:

SELECT TOP (1) WITH TIES name, SUM(sales) as total_sales
FROM employees
GROUP BY name
ORDER BY SUM(sales) DESC
于 2012-07-11T06:02:50.887 回答
0
SELECT name, SUM(sales) as total_sales
FROM employees
GROUP BY name
ORDER by total_sales DESC
LIMIT 1;

更好的解决方案是按员工 ID 分组,这样我们就可以确定他们是同一个人。因为可以有两个克里斯。

于 2012-07-10T22:27:38.667 回答
0

我会使用窗口分区

select * from
(
    select
        employee
    ,   sum(sales) as sales
    ,    row_number() over
    (
         order by sum(sales) desc
    ) as rank
    from EmployeeSales
    group by employee
) tmp
where tmp.rank = 1

我同意某人(Shawn)所说的关于为此使用员工ID 和分组而不是名称的说法。

(我从 row_number() 调用中删除了分区,因为它不需要它)

于 2012-07-10T22:44:28.100 回答
0

你可以使用 CTE

WITH CTE AS(选择员工,总和(销售额)作为销售额,ROW_NUMBER()超过(按员工排序按总和(销售额)递减)RN FROM EmployeeSales)选择员工,销售额来自CTE WHERE RN = 1

于 2012-07-11T06:07:12.840 回答