2017-03-05 131 views
0

好了,所以現在我拉取數據建立隊列分析,它看起來像這樣: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 |  | 

現在我進入excel並做SUMPRODUCT轉換它 - 這需要資源和時間。

是否有辦法直接從SQL中獲取第二個視圖?假設我是SQL 101請 - 我已經做了一個月。

回答

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

您還可以使用交叉表函數來創建數據透視表。 使用這些例子之前,你需要安裝擴展

創建擴展tablefunc

之後,您可以執行這個查詢。要實現dec 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)