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
CodePudding user response:
Yes, grouping does go hand in hand with aggregate functions, for any resulting column not contained within an aggregate function
CodePudding user response:
Grouping and the operations of aggregation are typically linked to three keywords:
- any aggregation function
- the
GROUP BYclause - the
DISTINCT (ON)modifier after theSELECTkeyword
You can use:
- aggregation functions alone when they are used on every field found inside the
SELECTstatement - the
GROUP BYclause 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 theSELECTstatement (really you should go withDISTINCT ON) - the
DISTINCTmodifier alone to select distinct rows (not fields) - the
DISTINCT ONmodifier only when accompanied by anORDER BYclause that defines the order for extracting the rows - aggregation functions the
GROUP BYclause, that is forced to contain all fields found in theSELECTstatement that are not object of aggregation - the
DISTINCTmodifier theGROUP BYclause - you can do it but theGROUP BYclause really is superfluous as it is already implied by theDISTINCTkeyword itself.
You can't use:
- aggregation functions the
GROUP BYclause when non-aggregated fields included in theSELECTstatement are not found within theGROUP BYclause - aggregation functions alone when in the
SELECTstatement 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.
