2016-11-25 98 views
0

我想知道是否有方法显示聚合结果上的多个列,但没有它影响组。如何继续执行此查询

我需要显示名称旁边的聚合结果,但我不知道我在这里失踪。

这是我的工作数据:

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

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

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

任何建议都会有所帮助。

谢谢。

+0

你想要的输出格式是什么?你想让你的查询返回一行吗?你想每年一行吗?等 – iamdave

+0

我需要每年一行(在这种情况下,我只会有两行),并且每行都会说明销售人员的姓名和销售总额。 – master2080

回答

1

这应该为你工作:FROM子句中

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. 
+0

谢谢!这工作!有什么机会可以解释如何? ^^ – master2080

+1

解释在代码中的注释中。这与您的查询相同,我刚刚用,,''符号替换了'适当的'内部连接'符号。唯一的实际区别是增加了'SalesRank'字段,该字段使用'窗口函数'来计算每年内总销售额的'row_number'。然后围绕这个选择只会返回那些SalesRank为1或最好的推销员。 – iamdave

1

首先,从未使用逗号。 总是使用明确的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表。