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

前端 未结 5 947
遥遥无期
遥遥无期 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:50

    Yes, grouping is done first, and it affects a single select whereas ordering affects all the results from all select statements in a union, such as:

    select a, 'max', max(b) from tbl group by a
    union all select a, 'min', min(b) from tbl group by a
    order by 1, 2
    

    (using field numbers in order by since I couldn't be bothered to name my columns). Each group by affects only its select, the order by affects the combined result set.

    It seems that what you're after can be achieved with:

    select A, max(B) from tbl group by A
    

    This uses the max aggregation function to basically do your pre-group ordering (it doesn't actually sort it in any decent DBMS, rather it will simply choose the maximum from an suitable index if available).

提交回复
热议问题