MySQL get percentage difference from current week to last week

I’m trying to calculate the difference between the summers of the current week and last week. The values are all stored in a table.

I already have the individual values of the current and last week, but how do I get it in a select that these values can be offset against each other, that the difference can be displayed in percent.

The Output must show for Example: +10% or -10% depending on whether the current value is higher or lower than the last.

I tried this, but it shows always an error:

SELECT views_current_week / views_last_week * 100 AS difference  FROM (     SELECT SUM(website_stats_homepage) as views_last_week       FROM website_stats      WHERE website_stats_date >= curdate() - INTERVAL dayofweek(curdate())+6 day          AND website_stats_date < curdate() - INTERVAL dayofweek(curdate())-1 day,      SELECT SUM(website_stats_homepage) as views_current_week      FROM website_stats      WHERE yearweek(DATE(website_stats_date), 1) = yearweek(curdate(), 1))  website_stats  
Add Comment
1 Answer(s)

I habe made a quick sqlfiddle which should do what you want. You have to take care of 0 results cause they can crash the division.

http://sqlfiddle.com/#!9/b8b906/2

To all sql cracks here. I know this can be much shorter and optimized but I thought I make it as easy to understand for a newbie as possible

Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.