2017-03-05 9 views
0

[OK]をので、今、私はSQLからデータを引っ張っすることだし、それは次のようになります。SQL - どのようにコホート分析を構築するために

Cohort  Date  Revenue 
--------------------------- 
Dec 16 Dec 16 30.00 
Dec 16 Jan 17 31.00 
Dec 16 Feb 17 32.00 
Jan 17 Jan 17 40.00 
Jan 17 Feb 17 41.00 
Feb 18 Feb 17 50.00 

私がしたいことはこれです:

Cohort |   Date   
     | Month0 | Month1 | Month2 
--------|--------|--------|-------- 
Dec 16 | 30.00 | 31.00 | 32.00 
Jan 17 | 40.00 | 41.00 | 
Feb 18 | 50.00 |  | 

今私は、それを変換するにはSUMPRODUCTを実行します。これはリソースと時間がかかります。

すぐにSQLの2番目のビューを取得する方法はありますか?私はSQL 101だとします - 私は1ヶ月間それをやっています。

答えて

0

ウィンドウ関数dense_rankを使用して、集計を使用してテーブルをピボットすることができます。

select cohort, 
    sum(case when rn = 1 then Revenue end) Month0, 
    sum(case when rn = 2 then Revenue end) Month1, 
    sum(case when rn = 3 then Revenue end) Month2 
from (
    select t.*, 
     dense_rank() over (
      partition by cohort order by to_date('01-' || date, 'dd-Mon-yy') 
      ) rn 
    from your_table t 
    ) t 
group by cohort 
+0

ありがとうございます。 –

0

また、クロス集計機能を使用してピボットテーブルを作成することもできます。あなたは、このクエリを実行することができた後EXTENSIONのtablefunc

をCREATE延長

をインストールする必要があり、これらの例を使用する前に 。 12月16日を達成するには、まず、年月日から始まるソートを行います。

select * 
from crosstab(
$$select t.cohort, 
     t.date, 
     sum(t.revenue) 
    from your_table t 
    group by t.cohort,t.date 
    order by to_char(to_date('01-'||t.cohort,'dd-Mon-yy'),'YYYYMMDD'), 
      to_char(to_date('01-'||t.date,'dd-Mon-yy'),'YYYYMMDD') asc 
$$) 
as months(cohort text,Month0 NUMERIC,Month1 NUMERIC,Month2 NUMERIC) 
関連する問題