2

我有大约35,000 行的销售快照。让我们调用这些列:

Sales Rep | Account ID | Total Contract Value | Date

我需要对所有内容进行分组Sales Rep,然后从那里根据2013 年 1 月 (Date) 的 >= $10,000Sales Rep位置选择前 35 个帐户Total Contract ValueTotal Contract Value

例如,假设 John Doe 从 1 月份开始在此表中有 294 个帐户,我只想查看他的前 35 个帐户 >= $10,000 ,Jane Doe 也是如此,等等。查询的资源效率非常重要尽可能使用。

想法?

4

2 回答 2

2

答案已经在您的标题中,由SalesRepAccountID和 Rank by划分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

于 2013-02-01T21:00:35.653 回答
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(),有一些效率较低的替代方法。

于 2013-02-01T21:16:36.310 回答