2016-10-27 47 views
0

我想在不使用分析函數的情況下獲取user_counts與昨天相比的更改百分比,因爲mysql不支持它。只是想知道什麼是解決問題的最好方法。用戶與昨天沒有LAG解析函數相比的用戶百分比

模式: - User_Visits(VisitorID,用戶名,日)

我已經試過?

SELECT Day, 
     FROM (
      (Day_User_Count - LAG(Day_User_Count, 1) OVER (ORDER BY Day))/ 
       Day_User_Count 
      )* 100 AS Percentage_Change  
     ( 
      SELECT Day, 
        COUNT(DISTINCT UserID) AS Day_User_Count 
      FROM User_Visits 
      GROUP BY Day 
     ); 
+0

爲什麼有人downvote如果我張貼的疑問句是一個有效的...感謝。 – Teja

回答

2

試試這個。

SELECT 
    Day, COUNT(DISTINCT UserID) as Day_count, prv.Prev_Day_User_Count, 
    (COUNT(DISTINCT UserID) - prv.Prev_Day_User_Count) 
     /prv.Prev_Day_User_Count * 100 AS Percentage_Change 
FROM 
    User_Visits UV 
     INNER JOIN 
    (SELECT 
     Day AS prev_day, 
      COUNT(DISTINCT UserID) AS Prev_Day_User_Count 
    FROM 
     User_Visits 
    GROUP BY Day) prv ON UV.day = DATE_ADD(prv.prev_day, INTERVAL 1 DAY) 
GROUP BY Day; 

輸入:

UserID Day  
1 2016-10-20 
1 2016-10-20 
2 2016-10-20 
3 2016-10-21 
4 2016-10-21 
5 2016-10-21 
6 2016-10-22 
1 2016-10-22 
2 2016-10-23 
3 2016-10-23 
4 2016-10-23 
5 2016-10-23 
6 2016-10-24 
7 2016-10-24 

輸出:

# Day, prev_day, Day_count, Prev_Day_User_Count, Percentage_Change 
'2016-10-21', '2016-10-20', '3', '2', '50.0000' 
'2016-10-22', '2016-10-21', '2', '3', '-33.3333' 
'2016-10-23', '2016-10-22', '4', '2', '100.0000' 
'2016-10-24', '2016-10-23', '2', '4', '-50.0000' 

http://sqlfiddle.com/#!9/d3bcb

+0

您正在添加1而不是-1 – Teja

+0

對,因爲如果我在昨天添加1天,那就等於今天。 – CGritton

+0

但是你在技術上沒有選擇昨天的權利..你只是改變了名字.. – Teja