Home > database >  Sum with multiple conditions and GROUP BY
Sum with multiple conditions and GROUP BY

Time:12-15

I have these 3 tables :

order_details

id date
5 15/12/2022
6 15/12/2022
7 16/12/2022

order_items

id orderId productId quantity
7 5 5 10
8 5 6 5
9 5 7 2
10 6 5 10
11 6 6 5
12 6 7 2
13 7 5 7
14 7 6 3

products

id name
5 productOne
6 productTwo
7 productThree

I want to join these 3 tables and have a list of products associated with their date and sum of the quantities

For example for these tables I want this:

date product_name quantity
15/12/2022 productOne 20
15/12/2022 productTwo 10
15/12/2022 productThree 4
15/12/2022 productOne 20
15/12/2022 productTwo 10
15/12/2022 productThree 4
16/12/2022 productOne 7
16/12/2022 productTwo 3

If someone can help me it would be so beautiful...

Here is my work on my side ->

SELECT *
  FROM order_details
  JOIN (SELECT order_items.orderId,
               order_items.productId,
               order_items.quantity,
               products.name,
               SUM(order_items.quantity)
          FROM order_items
         INNER JOIN products
            ON order_items.productId = products.id
         GROUP BY order_items.productId) AS items
 GROUP BY order_details.date, items.productId

CodePudding user response:

SELECT order_details.date, products.name, SUM(order_items.quantity) AS quantity
FROM order_details
INNER JOIN order_items ON order_details.id = order_items.orderId
INNER JOIN products ON order_items.productId = products.id
GROUP BY order_details.date, products.name
  • Related