Do MySQL aggregate functions always return a single row?

I apologize if this is really basic, but:

I feel that at some point I did not have this problem, and now I am, so either I did something completely different or my syntax skipped a step.

For example, I have a query that I need to return all rows with certain data along with another column that contains only one of these columns. If everything was as I expected, it would look like this:

 SELECT
 order_id,
 cost,
 part_id,
 SUM(cost) AS total
 FROM orders 
 WHERE order_date BETWEEN xxx AND yyy

And I would get all the lines with my orders, with the total amount superimposed on the end of each of them. I know that the total will be the same every time, but this was expected. Right now, to make this work, I use:

 SELECT
 order_id,
 cost,
 part_id,
 (SELECT SUM(cost)
 FROM orders
 WHERE order_date BETWEEN xxx AND yyy) AS total
 FROM orders 
 WHERE order_date BETWEEN xxx AND yyy

, , , . , , SUM , , , 3 , , , .

.

+3
1

GROUP BY , :

SELECT
order_id,
part_id,
SUM(cost) AS total
FROM orders 
WHERE order_date BETWEEN xxx AND yyy
GROUP BY order_id, part_id

. , , , order_id part_id - PK, SUM(cost) , , = cost ( , . ).

GROUP BY.

GROUP BY :

MySQL -


: , , , :

SELECT
or1.order_id,
or1.cost,
or1.part_id,
(
  SELECT SUM(cost)
  FROM orders or2
  WHERE or1.order_id = or2.order_id
  GROUP BY or2.order_id
) AS total
FROM orders or1
WHERE or1.order_date BETWEEN xxx AND yyy
+6

Source: https://habr.com/ru/post/1713730/


All Articles