ORDER BY条件为一组行

时间:2018-03-02 11:07:52

标签: mysql sql-order-by codeigniter-3

在这里,我想得到类似number行的结果,这意味着一个接一个,每行将有不同的数据计数,而具有更高计数的行应首先出现,这是我的代码

public function get_all_mostly_entered_numbers($limit,$offset)
{

    $query=$this->db->query("SELECT *, SUM(quantity) AS MOST_FREQUENT
         FROM datas
         WHERE date_status=1
         GROUP BY number,type
         ORDER BY SUM(quantity) DESC LIMIT 200");

    return $query->result();
}

结果就像这样

type        number       count
sup          555         280
sup          000         245
sup          777         235
sup          888         235
bo           000         40
bo           777         30
bo           888         25
bo           555         10

我希望我的结果像这样

type        number       count
sup          555         280
bo           555         10
sup          000         245
bo           000         40
sup          777         235
bo           777         30
sup          888         235
bo           888         25

2 个答案:

答案 0 :(得分:1)

查看提供的样本

你可以使用结果与最大结果和基于顺序的连接(在样本中有一个max_val列,以便更好地理解结果)

 {
    id:1,
    PostList:[
     {
     postname:"aaa",
     lastdatetime:2017-07-13T17:10:25+05:30,
     sname:"sas"
     },
     {
     postname:"aaa1",
     lastdatetime:2017-07-14T17:10:25+05:30,
     sname:"sasadd"
     },
     {
     postname:"aaa2",
     lastdatetime:2017-07-10T17:10:25+05:30,
     sname:"weq"
     }
    ]
    }

您无法显示max_val只需从结果(已订购)中选择您需要的列

为了避免使用相同max_row的错误序列,您可以尝试

 {
        id:2,
        PostList:[
         {
         postname:"aaa",
         lastdatetime:2017-07-13T17:10:25+05:30,
         sname:"sas"
         },
         {
         postname:"aaa1",
         lastdatetime:2017-07-14T17:10:25+05:30,
         sname:"sasadd"
         },
         {
         postname:"aaa2",
         lastdatetime:2017-07-10T17:10:25+05:30,
         sname:"weq"
         }
        ]
        }

答案 1 :(得分:0)

 $query=$this->db->query("SELECT *,T.number, max(T.MOST_FREQUENT), W.MOST_FREQUENT, W.Type
   from (

   SELECT *, SUM(quantity) AS MOST_FREQUENT
   FROM datas
   WHERE date_status=1
   GROUP BY number,type
   ORDER BY SUM(quantity) DESC LIMIT 200 ) T 
   INNER JOIN (
   SELECT *, SUM(quantity) AS MOST_FREQUENT
       FROM datas
       WHERE date_status=1
       GROUP BY number,type
       ORDER BY SUM(quantity) DESC LIMIT 200
         ) W ON T.number = W.number 
           group by T.number, W.MOST_FREQUENT, W.Type
           ORDER BY  max(T.MOST_FREQUENT)  DESC
           , (max(T.MOST_FREQUENT)=W.MOST_FREQUENT) DESC
           ,  W.MOST_FREQUENT
           , W.Type");

 return $query->result();

我改变了代码就像这样得到了结果

 type        number       count
sup          555         280
bo           555         10
sup          000         245
bo           000         40
sup          777         235
sup          888         235
bo           777         30
bo           888         25

如果两个数字具有相同的计数,则两个数字相继出现而不是选择相同的数字