选择截取月份的最后日期的期初余额和整月的其他金额的总和

时间:2015-05-23 15:50:09

标签: sql sql-server-2012

我有表balance_detail

sales_period    sales_date  opening_amt   sales_amt  payment_amt  closing_amt
-----------------------------------------------------------------------------
201501           01-01-2015                210        100          110
201501           02-01-2015   110          300        280          130
201501           03-01-2015   130                      50          80
201501           05-01-2015   80           600        670          10
201502           02-02-2015   10           160        100          70
201502           15-02-2015   70           100        170           0      

并希望得到这样的结果

sales_period    opening_amt   sales_amt  payment_amt  closing_amt
-----------------------------------------------------------------------------
 201501            80           1110      1110           10
 201502            70           260       270             0

1 个答案:

答案 0 :(得分:2)

一种方法是使用条件聚合和row_number()

select sales_period,
       max(case when seqnum = 1 then opening_amt end) as opening_amt,
       sum(sales_amt) as sales_amt,
       sum(payment_amt) as payment_amt,
       max(case when seqnum = 1 then closing_amt end) as closing_amt
from (select bd.*,
             row_number() over (partition by sales_period order sales_date desc) as seqnum
      from balance_detail bd
     ) bd
group by sales_period;