如何获得库存每月的月末余额

时间:2018-07-31 10:13:26

标签: sql sql-server

我有四列,如

Date            Customer        InvoiceNo            StockBalance
11/29/2017       A               IN000414             5000
11/30/2017       B               IN000415             4000 
12/27/2017       A               IN000416             3500
12/30/2017       B               IN000417             2000

我想获得每个月底的库存余额,我需要将输出作为

11/30/2017       B               IN000415             4000 
12/30/2017       B               IN000417             2000

我怎么能得到有人指导我?

2 个答案:

答案 0 :(得分:0)

您可以使用row_number()函数:

select t.*
from (select *, row_number() over (partition by year(date), month(date) order by date desc) seq
      from table
     ) t
where seq = 1;

编辑:您要apply

select t.*
from table t cross apply
     ( select top (1) t1.*
       from table t1
       where t1.Customer = t.Customer and
             EOMONTH(t1.Dat) = t.Dat
       order by t1.Dat desc
     ) t1;

答案 1 :(得分:0)

使用row_number(),但请确保在计算中包括年份和月份:

select t.*
from (select t.*,
             row_number() over (partition by year(date), month(date)
                                order by date desc
                               ) as seqnum
      from t
     ) t
where seqnum = 1;