简体   繁体   中英

Get value difference between two dates in MySQL

I have a following table structure:

page_id   view_count    date
1         30            2018-08-30
1         33            2018-08-31
1         1             2018-09-01
1         5             2018-09-02
...

View count is reset on 1st of every month, and it's current value is stored on a daily basis, so on 31st of August it was increased by 3 (because 33-30).

What I need to do is to retrieve the view count (difference) between two dates through SQL query. To retrieve view count between two dates in same month would be simple, by just subtracting bigger date with the lower date, but retrieving between two dates that are in different months is what's not sure to me how to achieve. If I wanted to retrieve data between 2018-08-13 and 2018-09-13 I would have to get difference between 2018-08-31 and 2018-08-13 , and add it to the value of 2018-09-13 .

Also, I would like to do it for all page_id at once, between the same dates if possible within a single query.

assuming that the counter is unique per page and that the page_id counter is inserted daily into the table, I think that such a solution would work

The dates are based on the example, and should be replaced by the relevant parameters

SELECT
    v1.view_count + eom.view_count - v2.view_count
FROM
    view_counts v1
    INNER JOIN view_counts v2 ON v2.page_id = v1.page_id AND v2.`date` = '2018-08-13'
    INNER JOIN view_counts eom ON v2.page_id = v.page_id AND eom.`date` = LAST_DAY(DATE_ADD(v.`date`, INTERVAL -1 MONTH))
WHERE
    `date` = '2018-09-13'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM