Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse a MySQL result

I need to reverse my output and I can't do it by switching the ORDER BY clause.

This code is getting the last 12 months, but I need to display them in the opposite order. Right now it has October first, but I need it to come last. If I switched to ORDER BY DATE ASC then I would get the wrong months.

My code is this:

<?php
$result2 = mysqli_query(
    $con,
    "SELECT SUM(DISTRIBUTED_AMOUNT / EXCHANGE_RATE)
        FROM royalties 
        GROUP BY DATE
        ORDER BY DATE DESC
        LIMIT 12"
);
while($row2 = mysqli_fetch_array($result2)) {
    echo number_format($row2[0], 2, '.', '') . ', ';
}?>
like image 753
Michael St Clair Avatar asked Jan 12 '23 23:01

Michael St Clair


1 Answers

You can just wrap your query in another select and reverse the order by:

SELECT res
FROM (
  SELECT `date`,SUM(DISTRIBUTED_AMOUNT / EXCHANGE_RATE) AS res
  FROM royalties
  GROUP BY `date`
  ORDER BY `date` DESC LIMIT 12
  ) a
ORDER BY `date` ASC
like image 54
Filipe Silva Avatar answered Jan 16 '23 22:01

Filipe Silva