如何继续此查询

时间:2016-11-25 14:03:45

标签: sql sql-server

我想知道是否有一种方法可以在聚合结果上显示多个列,但不会影响该组。

我需要在汇总结果旁边显示名称,但我不知道我在这里缺少什么。

这是我正在使用的数据:

enter image description here

这是以下查询的结果:

select * from Salesman, Sale,Buyer 
where Salesman.ID = Buyer.Salesman_ID and Buyer.ID = sale.Buyer_ID

我需要找到销售特定年份最多的东西(总价格)的推销员。

这是我到目前为止所做的:

select DATEPART(year,sale.sale_date)'year', Salesman.First_Name,sum(sale.price)
from Salesman, Sale,Buyer
where Salesman.ID = Buyer.Salesman_ID and Buyer.ID = sale.Buyer_ID
group by  DATEPART(year,sale.sale_date),Salesman.First_Name

这将返回每个销售员的总销售额。

enter image description here

如何从这里继续获得每年的顶级推销员?

也许我正在做的查询是完全错误的,还有更好的方法吗?

任何建议都会有所帮助。

感谢。

2 个答案:

答案 0 :(得分:1)

这应该适合你:

select *
from(
    select DATEPART(year,s.sale_date) as SalesYear  -- Avoid reserved words for object names
            ,sm.First_Name
            ,sum(s.price) as TotalSales
            ,row_number() over (partition by DATEPART(year,s.sale_date)  -- Rank the data within the same year as this data row.
                                order by sum(s.price) desc   -- Order by the sum total of sales price, with the largest first (Descending).  This means that rank 1 is the highest amount.
                                ) as SalesRank    -- Orders your salesmen by the total sales within each year, with 1 as the best.
    from Buyer b
        inner join Sale s
            on(b.ID = s.Buyer_ID)
        inner join Salesman sm
            on(sm.ID = b.Salesman_ID)
    group by  DATEPART(year,s.sale_date)
                ,sm.First_Name
    ) a
where SalesRank = 1    -- This means you only get the top salesman for each year.

答案 1 :(得分:1)

首先,从不FROM子句中使用逗号。 始终使用明确的JOIN语法。

您的问题的答案是使用窗口函数。如果存在平局,并且您想要所有值,则RANK()DENSE_RANK()。如果你总是想要一个 - 即使有关系 - 那么ROW_NUMBER()

select ss.*
from (select year(s.sale_date) as yyyy, sm.First_Name, sum(s.price) as total_price,
             row_number() over (partition by year(s.sale_date)
                                order by sum(s.price) desc
                               ) as seqnum
      from Salesman sm join
           Sale s
           on sm.ID = s.Salesman_ID 
      group by year(s.sale_date), sm.First_Name
     ) ss
where seqnum = 1;

请注意,此查询不需要Buyers表。