在SQL SERVER中同时从不同帐户的表中查找多个最大值

时间:2016-11-16 10:01:47

标签: sql-server-2008

假设我们有一个客户详细信息的数据转储filter 此记录包含多个invoiceDates数据。我必须获取具有最后三个invoiceDates的此类客户的记录。 (account, invoiceAmount, invoiceDate).

每个客户可能会有不同的发票。

[MAX(invoiceDate), MAX(invoiceDate)-1, MAX(invoiceDate)-2]

示例数据,我必须获取最后那些2个样本帐户的发票。

查询是什么?

1 个答案:

答案 0 :(得分:2)

由于您实际上没有在相同或不同的行中指定是否需要它,因此这两个解决方案都是:

-- Build up the test data:
declare @t table(account nvarchar(50), invoicedate date, ageamount int);
insert into @t values
,('1-129285408641','2016-01-08',1347)
,('1-129285408641','2015-11-08',442 )
,('1-129285408641','2015-08-08',409 )
,('1-129285408641','2015-12-08',918 )
,('1-129285408641','2015-07-08',109 )
,('1-129285408641','2016-04-08',421 )
,('1-129285650772','2016-04-08',637 )
,('1-129285650772','2016-09-08',1000)
,('1-129285408641','2016-09-08',119 )
,('1-129285408641','2016-10-08',1228);


-- To return last three invoice dates in the same row:
with cte
as
(
    select account
            ,invoicedate
            ,row_number() over (partition by account order by invoicedate desc) as rownum
    from @t e
)
select Account
        ,[1] as MostRecentInvoiceDate
        ,[2] as SecondMostRecentInvoiceDate
        ,[3] as ThirdMostRecentInvoiceDate
from 
( 
    select c.account
            ,c.invoicedate
            ,c.rownum
    from cte c 
        join @t t on c.account = t.account
    where c.rownum <= 3
)a
pivot
    (
    max(invoicedate) for rownum in ([1],[2],[3])
    ) pvt1;


-- To return last three invoice dates as seperate rows:
with cte
as
(
    select account
            ,invoicedate
            ,row_number() over (partition by account order by invoicedate desc) as rownum
    from @t e
)
select Account
        ,InvoiceDate
        ,rownum
from cte
where rownum <= 3
order by account
        ,invoicedate desc;