MySQL - How to calculate the product of multiple rows of one column

Narktor :

I have the following table:

select * from bestelldetails WHERE `Bestell-Nr` = 10870;
+------------+------------+-------------+--------+--------+
| Bestell-Nr | Artikel-Nr | Einzelpreis | Anzahl | Rabatt |
+------------+------------+-------------+--------+--------+
|      10870 |         35 |          18 |      3 |      0 |
|      10870 |         51 |          53 |      2 |      0 |
+------------+------------+-------------+--------+--------+

Now, first I calculated the product of each rows "Einzelpreis (=price per piece)" and "Anzahl (pieces)" like this:

select *, Einzelpreis * Anzahl AS Rechnungssumme from bestelldetails WHERE `Bestell-Nr` = 10870;
+------------+------------+-------------+--------+--------+----------------+
| Bestell-Nr | Artikel-Nr | Einzelpreis | Anzahl | Rabatt | Rechnungssumme |
+------------+------------+-------------+--------+--------+----------------+
|      10870 |         35 |          18 |      3 |      0 |             54 |
|      10870 |         51 |          53 |      2 |      0 |            106 |
+------------+------------+-------------+--------+--------+----------------+

But now I want the SUM of each set of Data of "Bestell-Nr". I tried like this:

select *, Einzelpreis * Anzahl AS Rechnungssumme from bestelldetails WHERE `Bestell-Nr` = 10870 GROUP BY `Bestell-Nr`;
+------------+------------+-------------+--------+--------+----------------+
| Bestell-Nr | Artikel-Nr | Einzelpreis | Anzahl | Rabatt | Rechnungssumme |
+------------+------------+-------------+--------+--------+----------------+
|      10870 |         35 |          18 |      3 |      0 |             54 |
+------------+------------+-------------+--------+--------+----------------+

But this obviously doesnt work. Inside "Rechnungssumme", only the product of ONE record is displayed, not the sum of all the values aggregated from each set of data.

In my actual usecase, there will be tens of thousands of different orders, all with their own "Bestell-Nr". For each of these orders, this operation must create aggregated rows where the SUM of the products of each row must be calculated and correctly displayed.

DmitriyH :

Is it what you need?:

select sum(Anzahl) as Anazahl, sum(`Artikel-Nr`) as `Artikel-Nr`, sum(Einzelpreis) as Einzelpreis, sum(Rabatt) as  Rabatt, sum(Einzelpreis * Anzahl) as Rechnungssumme, `Bestell-Nr` from bestelldetails GROUP BY `Bestell-Nr` HAVING `Bestell-Nr`=10870

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=372615&siteId=1