按多列排序sql结果时出现问题

时间:2014-09-23 09:16:04

标签: php mysql sql distinct

year  monthnumber  sales
------------------------
2014       8       2800
2014       9       3000
2013      11       2120
2014       8       2700
2013       7       2600
2013      12       2100

我需要显示列的所有独特组合"年"和" monthnumber"。我在排序结果时遇到麻烦,以便首先显示最新的组合(2014年9月)。结果应该是:

september 2014
august 2014
december 2013
november 2013
july 2013

到目前为止,下面的代码给出了以下结果(因此在订购月份时出现问题):

september 2014
august 2014
july 2013
december 2013
november 2013

PHP / SQL:

<?php
 $sql = "SELECT DISTINCT (case  when monthnumber = '1' then 'january'
                                when monthnumber = '2' then 'february'
                                when monthnumber = '3' then 'march'
                                when monthnumber = '4' then 'april'
                                when monthnumber = '5' then 'may'
                                when monthnumber = '6' then 'june'
                                when monthnumber = '7' then 'july'
                                when monthnumber = '8' then 'august'
                                when monthnumber = '9' then 'september'
                                when monthnumber = '10' then 'october'
                                when monthnumber = '11' then 'november'
                                when monthnumber = '12' then 'december'
                         end) AS monthname, year from `exampletable` ORDER BY year DESC, monthnumber DESC";

 $stmt = $pdo->prepare($sql);
 $stmt->execute();

 if($stmt->rowCount())
 {
 while ($result = $stmt->fetch(PDO::FETCH_ASSOC))
 {
?>

<?php echo strtolower($result['monthname']);?> <?php echo $result['year'];?>

<?php
 }// end while
 }// end if
 else {
 echo '0 results';
 }// end else
?>

我在这里缺少什么?

2 个答案:

答案 0 :(得分:1)

我怀疑您需要将MonthNumber投射到INTEGER子句中的ORDER BY

ORDER BY year DESC, CAST(monthnumber AS UNSIGNED) DESC

答案 1 :(得分:1)

如果MontNumber是一个字符串,那么排序顺序首先在第一个字符上完成,然后在第二个字符上完成;当按下降顺序排序时,应该给出类似下面的内容:

9 8 7 6 五 4 3 2 12 11 10 1

如另一个答案中所述,您必须首先将MonthNumber从字符串转换为整数。