2016-08-28 83 views
0

如何轉置此表,所以我有兩列,一列顯示付費用戶的比例和一列顯示免費用戶的比例。另外,在我的腳本中,有什麼方法可以讓代碼更加簡潔,'SQL'就像?我似乎也無法在sqlfiddle中使用select語句創建表,因爲我得到一個錯誤,說它只能在模式屏幕中創建。無論如何,我可以將sql語句嵌入到新表中嗎?最簡潔的方式轉置SQL表

我已經創建了sqlfiddle一個腳本,計算不同類型的用戶的一些下載指標:http://sqlfiddle.com/#!9/79bea4/1

+0

爲什麼這個問題downvoted,除了是凌亂? –

回答

1
SELECT df.Date, 
     SUM(CASE WHEN ad.paying_customer = 'No' 
       THEN df.downloads ELSE 0 END)/
     SUM(CASE WHEN ad.paying_customer = 'No' THEN 1 ELSE 0 END) AS `Average Downloads/Free User`, 
     SUM(CASE WHEN ad.paying_customer = 'Yes' 
       THEN df.downloads ELSE 0 END)/
     SUM(CASE WHEN ad.paying_customer = 'Yes' THEN 1 ELSE 0 END) AS `Average Downloads/Paid User` 
FROM 
(
    SELECT date, 
      user_id, 
      SUM(downloads) AS downloads 
    FROM download_facts 
    GROUP BY date, 
      user_id 
) df 
INNER JOIN user_dimension ud 
    ON df.user_id = ud.user_id 
INNER JOIN account_dimension ad 
    ON ud.account_id = ad.account_id 
GROUP BY df.Date 

演示在這裏:

SQLFiddle

1

您可以通過計算平均取下載的總和併除以用戶的數量。然後count(distinct)可以得到每個組中的用戶:

select df.date, 
     (sum(df.downloads)/
     count(distinct case when ad.paying_customer = 'No' then df.user_id end) 
     ) as avg_free, 
     (sum(df.downloads)/
     count(distinct case when ad.paying_customer = 'Yes' then df.user_id end) 
     ) as avg_paying 
from download_facts df left join 
    user_dimension ud 
    on df.user_id = ud.user_id left join 
    account_dimension ad 
    on ad.account_id = ud.account_id 
group by df.date; 
相關問題