Any reason for GROUP BY clause without aggregation function?

后端 未结 5 1379
心在旅途
心在旅途 2020-12-06 09:19

I\'m (thoroughly) learning SQL at the moment and came across the GROUP BYclause.

GROUP BY aggregates or groups the resultset according to t

相关标签:
5条回答
  • 2020-12-06 10:06

    Group by can used in Two way Majorly
    1)in conjunction with SQL aggregation functions
    2)to eliminate duplicate rows from a result set

    SO answer to your question lies in second part of USEs above described.

    0 讨论(0)
  • 2020-12-06 10:13

    Note: everything below only applies to MySQL

    GROUP BY is guaranteed to return results in order, DISTINCT is not.

    GROUP BY along with ORDER BY NULL is of same efficiency as DISTINCT (and implemented in the say way). If there is an index on the field being aggregated (or distinctified), both clauses use loose index scan over this field.

    In GROUP BY, you can return non-grouped and non-aggregated expressions. MySQL will pick any random values from from the corresponding group to calculate the expression.

    With GROUP BY, you can omit the GROUP BY expressions from the SELECT clause. With DISTINCT, you can't. Every row returned by a DISTINCT is guaranteed to be unique.

    0 讨论(0)
  • 2020-12-06 10:17

    You can perform a DISTINCT select by using a GROUP BY without any AGGREGATES.

    0 讨论(0)
  • 2020-12-06 10:22

    is the GROUP BY statement in any way useful without an accompanying aggregate function?

    Using DISTINCT would be a synonym in such a situation, but the reason you'd want/have to define a GROUP BY clause would be in order to be able to define HAVING clause details.

    If you need to define a HAVING clause, you have to define a GROUP BY - you can't do it in conjunction with DISTINCT.

    0 讨论(0)
  • 2020-12-06 10:23

    It is used for more then just aggregating functions.

    For example, consider the following code:

    SELECT product_name, MAX('last_purchased') FROM products GROUP BY product_name
    

    This will return only 1 result per product, but with the latest updated value of that records.

    0 讨论(0)
提交回复
热议问题