简体   繁体   中英

SQL select rows based on newest date, with sum of older included?

I have a complex (well, to me anyway) problem. Here's the short version. Maybe if I can get a little help with this small portion I won't need help with the larger portion.

Anyway, lets say I have a table with a few sample lines:

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

What the boss wants is, a list containing one line for each buyer, with the most recent salesman, and the total sales. The ideal output from above would be (the date can be used for comparison purposes, but he doesn't want it on the report):

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

How would that be best accomplished? I tried a self-join with an attempt to compare dates but I got an arithmetic overflow. I must have the verbage wrong. Any ideas?

;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

Here's an example using row number and sum windowing functions:

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

The initial "with SampleData..." part is just to have some sample data to write the query with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM