0

Question in the title. Thanks for the time.

EXAMPLE v

SELECT
  customer_id,
  SUM(unit_price * quantity) AS total_price
FROM orders o
JOIN order_items oi
  ON o.order_id = oi.order_id
GROUP BY customer_id

BarBaro
  • 5
  • 2
  • Does this answer your question? [Why do we need GROUP BY with AGGREGATE FUNCTIONS?](https://stackoverflow.com/questions/13998552/why-do-we-need-group-by-with-aggregate-functions) – Ocaso Protal Jul 05 '22 at 12:47
  • 1
    "*Question in the title*" - that's not what the title is for. The full question should be part of the question. The title should be a short abstract –  Jul 05 '22 at 12:52
  • My mistake. Won't happen again. – BarBaro Jul 16 '22 at 12:22

2 Answers2

0

Yes, grouping does go hand in hand with aggregate functions, for any resulting column not contained within an aggregate function

Daryl Wenman-Bateson
  • 3,870
  • 1
  • 20
  • 37
  • GROUP BY is not required if you only have aggregate functions in the SELECT list, e.g. `select SUM(unit_price * quantity) from order_items` –  Jul 05 '22 at 13:02
0

Grouping and the operations of aggregation are typically linked to three keywords:

You can use:

  • aggregation functions alone when they are used on every field found inside the SELECT statement
  • the GROUP BY clause alone - an allowed bad practice as you're intending to do an aggregation on your field but you're not specifying any aggregation function inside the SELECT statement (really you should go with DISTINCT ON)
  • the DISTINCT modifier alone to select distinct rows (not fields)
  • the DISTINCT ON modifier only when accompanied by an ORDER BY clause that defines the order for extracting the rows
  • aggregation functions + the GROUP BY clause, that is forced to contain all fields found in the SELECT statement that are not object of aggregation
  • the DISTINCT modifier + the GROUP BY clause - you can do it but the GROUP BY clause really is superfluous as it is already implied by the DISTINCT keyword itself.

You can't use:

  • aggregation functions + the GROUP BY clause when non-aggregated fields included in the SELECT statement are not found within the GROUP BY clause
  • aggregation functions alone when in the SELECT statement they are found together with non-aggregated fields.

When you can't aggregate because you need to select multiple fields, typically window functions + filtering operations (with a WHERE clause) can come in handy for computing values and row by row and removing unneeded records.

lemon
  • 14,875
  • 6
  • 18
  • 38