Kliptu
Kliptu

Reputation: 199

mysql get latest date record in ascending order

I have following "stats" table:

enter image description here

I want mysql query that return latest 5 date with sum of clicks. So starting record should be 2015-01-12

Output:

enter image description here

So far i have written following query that doesn't work according to my output.

SELECT logdate, (
    SELECT SUM(clicks)
    FROM stats t2
    WHERE t2.logdate = t1.logdate
    ORDER BY t2.logdate
    DESC LIMIT 0,5
) as clicks
FROM stats t1
GROUP BY t1.logdate
ORDER BY t1.logdate ASC
LIMIT 0, 5

Upvotes: 1

Views: 2754

Answers (1)

Hanky Panky
Hanky Panky

Reputation: 46900

Why such a complicated query? You can simply do

SELECT logdate,sum(clicks) FROM stats
GROUP BY logdate 
ORDER BY logdate DESC
LIMIT 5

Edit after your comment

SELECT * FROM
(
 SELECT logdate,sum(clicks) FROM stats
 GROUP BY logdate 
 ORDER BY logdate DESC
 LIMIT 5
) data
 ORDER BY logdate ASC

Fiddle

Upvotes: 5

Related Questions