从表中获取最大的SUM

时间:2012-07-10 22:22:04

标签: sql sql-server tsql

我正在努力让销售额最高的员工

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

我做错了什么?

5 个答案:

答案 0 :(得分: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小提琴示例: http://sqlfiddle.com/#!3/bd772/2

答案 1 :(得分: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

答案 2 :(得分:0)

SELECT name, SUM(sales) as total_sales
FROM employees
GROUP BY name
ORDER by total_sales DESC
LIMIT 1;

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

答案 3 :(得分: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)关于为此而拥有一个employeeID和group,而不是名字。

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

答案 4 :(得分:0)

你可以使用CTE

WITH CTE      AS(选择员工,总和(销售额)作为销售额,                 ROW_NUMBER()OVER(按员工划分ORDER BY sum(sales)desc)RN          来自EmployeeSales) 选择员工,        销售 来自CTE RN = 1