2016-09-05 5 views
1

の1のため、私は支払いのテーブルを持って、関連するデータはこのフォールドと合計グループのみまず、多くの種類

id  | price | type  | ts 
------ | -------|----------|--------------------------- 
1  | 50  | Payment | 2016-06-24 16:01:00.000000 
2  | 15  | Payment | 2016-06-24 16:02:00.000000 
3  | 5  | Refund | 2016-06-24 16:03:00.000000 
4  | 10  | Payment | 2016-06-24 16:04:00.000000 
5  | 20  | Payment | 2016-06-24 16:05:00.000000 
6  | 40  | Withdraw | 2016-06-24 16:06:00.000000 
7  | 30  | Withdraw | 2016-06-24 16:07:00.000000 
8  | 15  | Payment | 2016-06-24 16:08:00.000000 
9  | 25  | Payment | 2016-06-24 16:09:00.000000 

どのように見えるか私が欲しいのはの形にタイプ=「支払い」ですべての行を折るれます合計は、開始と終了の期間、他のすべてが同じでなければならないので、結果は、この

id  | price | type  | begin      | end 
------ | -------|----------|---------------------------|--------------------------- 
null | 65  | Payment | 2016-06-24 16:01:00.000000| 2016-06-24 16:02:00.000000 
3  | 5  | Refund | 2016-06-24 16:03:00.000000| 
null | 30  | Payment | 2016-06-24 16:04:00.000000| 2016-06-24 16:05:00.000000 
6  | 40  | Withdraw | 2016-06-24 16:06:00.000000| 
7  | 30  | Withdraw | 2016-06-24 16:07:00.000000| 
null | 40  | Payment | 2016-06-24 16:08:00.000000| 2016-06-24 16:09:00.000000 

も、それはいくつかのフラグが行で好きだった場合はグループ化され、最終的な結果を制限するためのサポートされて有用であろうように見えます

リグHT今私は遅れにより、ROW_NUMBER、グループをしようで停止、およびその他の、カントは、正しい方法

UPD見つける:これは少しトリッキーですhttp://sqlfiddle.com/#!15/3cfea/1/0

答えて

2

結果に取り組んでSQLバイオリンへのリンクを。行番号の違いを利用して、支払いのグループを取得することができます。次に、caseを使用して、支払い自体(それ以外の値ではなく)にのみ適用することができます。これは次のようになります。

select (case when type <> 'payment' then id) as id, 
     sum(price) as price, 
     min(type) as type, 
     min(ts) as begin, 
     max(case when type = 'payment' then ts end) as end 
from (select t.*, 
      (row_number() over (order by id) - 
       row_number() over (partition by type order by id) 
      ) as grp 
     from t 
    ) t 
group by (case when type = 'payment' then grp end), 
     (case when type <> 'payment' then id end); 
+0

近くに、しかし、私は、期待しないで何をここにリンクhttp://sqlfiddle.com/#!15/db9f6/1/0 – Neonailol

+0

私の悪い、忘れてしまったため、感謝のhttp:// sqlfiddle.com/#!15/3cfea/1/0 – Neonailol

関連する問題