使用GROUP或RANK中的WHERE的SQL语句

时间:2013-02-01 20:55:29

标签: sql group-by where ranking

我有一个约 35,000行的销售快照。我们打电话给专栏:

Sales Rep | Account ID | Total Contract Value | Date

我需要按Sales Rep对所有内容进行分组,然后从那里选择Sales Rep前35个帐户,基于Total Contract Value,其中Total Contract Value是> = 2013年1月(日期)的10,000美元

因此,举例来说,约翰·多伊从1月开始在此表中拥有294个帐户,我只想看到他的前35个帐户> = $ 10,000,对于Jane Doe等同等。查询如此非常重要尽可能高效地利用资源。

思想?

2 个答案:

答案 0 :(得分:2)

答案已在您的标题中,按SalesRepAccountID划分,按Total Contact Value排名。

SQL Server解决方案如下:

DECLARE @minimumValue decimal(20,2) = 10000
DECLARE @numberOfAccounts int = 35
DECLARE @from datetime = '1/1/2013'
DECLARE @till datetime = DATEADD(MONTH, 1, @from)

SELECT 
  [sub].[Sales Rep],
  [sub].[Rank],
  [sub].[Account ID],
  [sub].[Total Contract Value]
FROM
(
  SELECT
    [Sales Rep],
    [Account ID],
    [Total Contract Value],
    DENSE_RANK() OVER (PARTITION BY [Sales Rep] ORDER BY [Total Contract Value] DESC) AS [Rank]
  FROM [Sales]
  WHERE
    [Total Contract Value] >= @minimumValue
    AND [Date] > @from
    AND [Date] < @till
) AS [sub]
WHERE [sub].[Rank] <= @numberOfAccounts
ORDER BY 
  [Sales Rep] ASC,
  [Rank] ASC

这是(简单)Sql Fiddle

答案 1 :(得分:0)

为此,您需要使用名为row_number()的函数:

select ss.*
from (select ss.*, row_number() over (partition by salesrep order by ContractValue desc) as seqnum
      from snapshot ss
      where TotalContractValue >= 10000 and date between '2013-01-01' and '2013-01-31'
     ) ss
where seqnum <= 35

您没有指定您正在使用的数据库。在没有row_number()的数据库中,存在效率较低的替代方案。