Is there a [straightforward] way to order results *first*, *then* group by another column, with SQL?

前端 未结 5 966
遥遥无期
遥遥无期 2021-01-12 19:07

I see that in SQL, the GROUP BY has to precede ORDER BY expression. Does this imply that ordering is done after grouping discards identical rows/columns?

Because I s

5条回答
  •  忘掉有多难
    2021-01-12 19:42

    create table user_payments
    (
        phone_nr int NOT NULL,
        payed_until_ts datetime NOT NULL
    )
    
    insert into user_payments
    (phone_nr, payed_until_ts)
    values
    (1, '2016-01-28'), -- today
    (1, '2016-01-27'), -- yesterday  
    (2, '2016-01-27'), -- yesterday 
    (2, '2016-01-29')  -- tomorrow
    
    select phone_nr, MAX(payed_until_ts) as latest_payment
    from user_payments
    group by phone_nr
    
    -- OUTPUT:
    -- phone_nr latest_payment
    -- 1        2016-01-28 00:00:00.000
    -- 2        2016-01-29 00:00:00.000
    

    In the above example, I have used datetime column but similar query should work for timestamp column.

    The MAX function will basically do the "ORDER BY" payed_until_ts column and pick the latest value for each phone_nr. Also, you will get only one value for each phone_nr due to "GROUP BY" clause.

提交回复
热议问题