«column must appear in GROUP BY» чинят добавлением всех столбцов — строки взрываются. Почему?
Ожидаемый результат — одна строка на клиента с его суммарной выручкой. Первая попытка дала column "order_date" must appear in the GROUP BY clause, поэтому аналитик добавил все выбранные столбцы в GROUP BY. Теперь выходит по строке на заказ.
SELECT customer_id, order_date, SUM(amount) AS revenue
FROM orders
GROUP BY customer_id, order_date;
Объясните ошибку и почините до одной строки на клиента.
Ошибка значит, что выбранный столбец (order_date) не сгруппирован и не в агрегате. Добавление всех столбцов в GROUP BY меняет гранулярность на группу на строку, поэтому ничего не сворачивается. Чините группировкой по ключу (customer_id), оборачивая лишние в MAX().
- ✗Добавлять все столбцы в GROUP BY, чтобы убрать ошибку
- ✗Думать, что больше столбцов в GROUP BY уменьшат результат
- ✗Хвататься за DISTINCT вместо правки гранулярности
- →Когда группировка по двум столбцам — действительно то, что нужно?
- →Почему SELECT * с GROUP BY редко имеет смысл?
The message column "order_date" must appear in the GROUP BY clause is telling you that order_date is in the SELECT list but is neither a grouping key nor inside an aggregate — SQL cannot decide which of a group's many order_date values to show.
Adding it to GROUP BY silences the error but changes the question: the grouping grain becomes (customer_id, order_date), so each distinct order date starts its own group. With one order per date, that is one group per order — the row count "explodes" back to the raw table.
Group by the real key only, and either drop order_date or aggregate it:
SELECT customer_id, SUM(amount) AS revenue
FROM orders
GROUP BY customer_id;
-- if you need a date, aggregate it:
SELECT customer_id, MAX(order_date) AS last_order, SUM(amount) AS revenue
FROM orders
GROUP BY customer_id;