2017-04-05 11 views
-1

私は月ごとにグループ化された合計残高(デビット・クレジット)を返すクエリを持っています。 4列あります。先月の残高と当月の残高の合計

  1. ID
  2. 私は何をしたいか月
  3. 閉会バランス
  4. 開始残高

現在の月の期首残高値に先月のバランス値を取得することです。例えば; 2月の終値残高が100.000 $だとしましょう。その後、3月の開始価額も100,000 $にする必要があります。

スタイリングにごめんなさい。私はそれについてとても悪いです。ここにサンプルデータがあります。 Here is the sample data.

私は三月のOPEN_BALANCE細胞上の-14.830.707,59値を求めています。テーブルスキーマ、例えば、データ、または所望の結果なし

+0

行データを共有してください。 –

答えて

0

...このような何か:

row_number()left joincommon table expressionを使用 common table expressionouter apply()

;with cte (
    select 
     Id 
    , MonthDate = dateadd(month, datediff(month, 0, [Date]), 0) /* date datatype */ 
    , ClosingBalance = sum(debit)-sum(credit) 
    from t 
    group by 
     Id 
    , dateadd(month, datediff(month, 0, [Date]), 0) 
) 
select 
    Id 
    , MonthDate 
    , Month = datename(month, MonthDate) 
    , ClosingBalance 
    , OpeningBalance = x.OpeningBalance 
from cte 
    outer apply (
    select top 1 
     OpeningBalance = i.ClosingBalance 
    from cte as i 
    where i.Id = cte.Id 
     and i.MonthDate < cte.MonthDate 
    order by i.MonthDate desc 
) as x 

を使用

;with cte (
    select 
     Id 
    , MonthDate = dateadd(month, datediff(month, 0, [Date]), 0) /* date datatype */ 
    , ClosingBalance = sum(debit)-sum(credit) 
    , rn = row_number() over (
     partition by Id 
     order by dateadd(month, datediff(month, 0, [Date]), 0) 
     ) 
    from t 
    group by 
     Id 
    , dateadd(month, datediff(month, 0, [Date]), 0) 
) 
select 
    cte.Id 
    , cte.MonthDate 
    , Month = datename(month, cte.MonthDate) 
    , cte.ClosingBalance 
    , OpeningBalance = i.ClosingBalance 
from cte 
    left join cte as x 
    on x.Id = cte.Id 
     and x.rn = cte.rn-1