Sort data (order by) before group by in mysql

后端 未结 4 1890
说谎
说谎 2021-01-22 08:54

I want to group below data from sub_prd_id. but before that i need order data from max created_at.

I wrote query as below.

4条回答
  •  梦毁少年i
    2021-01-22 09:07

    What you're trying to accomplish is known as a groupwise maximum, which can't be achieved using ORDER BY. Instead, one must find the MAX() and then join the result back to the table:

    SELECT prd_data.* FROM prd_data NATURAL JOIN (
      SELECT   sub_prd_id, MAX(created_at) created_at
      FROM     prd_data
      GROUP BY sub_prd_id
    ) t
    

    See it on sqlfiddle.

提交回复
热议问题