I have the following SQL statement. It selects the visit count (vc
) for a particular date (vd
)
SELECT count(vid) vc, date(visitwhen) vd
FROM book_visit
where date(visitwhen) >=date_sub(now(), interval 14 day)
group by vd
order by vd desc
This selects a range of data and the output would look like this:
{
"data": [
{
"vc": 2,
"vd": "2023-04-25"
},
{
"vc": 1,
"vd": "2023-04-24"
},
{
"vc": 84,
"vd": "2023-04-23"
},
{
"vc": 17,
"vd": "2023-04-21"
},
{
"vc": 26,
"vd": "2023-04-20"
},
{
"vc": 1,
"vd": "2023-04-19"
},
{
"vc": 3,
"vd": "2023-04-17"
},
{
"vc": 18,
"vd": "2023-04-16"
},
....
What I would like to see is:
- If the
vc
in onevd
is larger/smaller than the previous or nextvc
/vd
, I would also like to return a+
(or-
) or whatever that is indicative of avc
increase / decrease.
I can do this probably at the client side, but I would like to see if it is possible to do so in MySQL.
2
Answers
Try something like this, if your MySQL supports:
This will result in something like this for some test data:
First order by date – Keep
@oldnum = num
at the end, so that for the first record, it will be NULL. From 2nd record onward, it will have the value of the previous record.IF
should be done before@oldnum = num
.IF
will decide what is the change in the current record innum
as compared to previous record’snum
available asoldnum
.Yes, or, as @user1191247 has suggested, for MySQL 8+: https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptions.html
Your current date criterion is non-sargable, as the server has to apply the
DATE()
function to the column value before it can be compared:should be changed to:
and make sure you have an index on
visitwhen
.You can use the LAG() window function to get the previous row’s value for a given expression:
Output: