Sort data (order by) before group by in mysql

后端 未结 4 1934
说谎
说谎 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条回答
  •  耶瑟儿~
    2021-01-22 09:17

    Your hunch was correct. This will so it:

    select * from
      (select * from prd_data order by created_at desc) x
    group by sub_prd_id
    

    Note that this is a mysql only solution, but since the question was tagged mysql that should be OK. Mysql has special functionality regarding group by when only some of the non-aggregated columns are grouped-by: whereas all other databases disallow this, mysql returns the first row encountered for each unique group by combination. By sorting before grouping, you get the rows with the latest created_at value for each sub_prd_id.

提交回复
热议问题