我希望在没有使用分析函数的情况下获得user_counts的更改百分比,因为mysql不支持它。只是想知道什么是解决它的最佳方法。
架构: - User_Visits(VisitorID,UserID,Day)
我尝试了什么?
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 :(得分: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'