SQL根据最新日期选择行,包括较旧的总和?

时间:2013-12-10 20:51:56

标签: sql sql-server sql-server-2008-r2

我有一个复杂的(好吧,对我来说)问题。这是简短的版本。也许如果我能从这一小部分得到一些帮助,我将不需要更大部分的帮助。

无论如何,假设我有一张包含几个样本行的表格:

CustNum - CustName - Salesman - Address - SoldTotal - SaleDate
a500 - bubby's - 03 - 123 Street - $254 - 03-13-2013
a500 - bubby's - 22 - 123 Street - $996 - 05-12-2013
a500 - bubby's - 13 - 123 Street - $1001 - 09-20-2013
b100 - squirrely's - 14 - 456 Street - $460 - 03-14-2013

老板想要的是一个列表,其中包含每位买家的一行,最近的推销员和总销售额。上面的理想输出是(日期可以用于比较目的,但他不想在报告中使用它):

CustNum - CustName - Salesman - Address - SoldTotal 
a500 - bubby's - 13 - 123 Street - $2251 
b100 - squirrely's - 14 - 456 Street - $460 

如何最好地完成?我尝试自我加入尝试比较日期,但我得到了算术溢出。我必须弄错了。有任何想法吗?

2 个答案:

答案 0 :(得分:3)

;WITH x AS 
(
  SELECT CustNum, CustName, SalesMan, Address, 
    s = SUM(SoldTotal) OVER (PARTITION BY CustNum),
    r = ROW_NUMBER() OVER (PARTITION BY CustNum ORDER BY SaleDate DESC)
  FROM dbo.YourTable
)
SELECT CustNum, CustName, SalesMan, Address, SoldTotal = s
  FROM x
  WHERE r = 1;

SQL Fiddle demo

答案 1 :(得分:1)

以下是使用行号和求和窗口函数的示例:

with SampleData (CustNum, CustName, Salesman, Address,  SoldTotal, SaleDate ) as (
    select 'a500', 'bubbys', '03', '123 Street', 254, '03-13-2013' union all
    select 'a500', 'bubbys', '03', '123 Street', 996, '05-12-2013' union all
    select 'b100', 'squirrelys', '14', '456 Street', 460, '03-14-2013'
)
select CustNum, CustName, MostRecentSalesman, SoldTotal
from (
    select
        CustNum
    ,   CustName
    ,   MostRecentSalesman = Salesman
    ,   rn = row_number() over (partition by CustNum order by SaleDate desc)
    ,   SoldTotal = sum(soldTotal) over (partition by CustNum)
    from SampleData
) x
where x.rn = 1

最初的“with SampleData ...”部分只是要用一些示例数据来编写查询。