Hello I’m struggling with how to solve an issue and have attempted sub-selects and joins however can’t get the result I need. Below is an over-simplified database schema.
The outcome I’m looking for is to be able to provide the SUM(order_items.quantity) grouped by sessions.start_time.
Where this gets complicated is that not all entires in order_items have a valid session_id. There is one entry that does though and they have the order_id in common.
For example (order_items table assuming session_id = start_date 01-02-2024):
ID | Order_id | Session_id | qty |
---|---|---|---|
1 | 1 | 1 | 2 |
2 | 1 | NULL | 5 |
3 | 2 | 1 | 2 |
4 | 2 | -1 | 2 |
The intended output would be
start_date | SUM(qty)
01-02-2024 | 11
In essence I need some sort of join/sub select that can provide the SUM(order_items.quantity) grouped by sessions.start_time however can someone use the fact there is one order_items entry with a valid session_id and the rest have the order_items.order_id in common.
I’ve tried various types of join (right, left etc) to no avail
Orders
- ID -int
Order_Items
- ID -int
- Order_ID -int
- Session_ID -int
- quantity -int
Sessions
- ID -int
- start_time -datetime
2
Answers
This quert sum the quantities from
order_items
by associating validSession_IDs
and then linking them tosessions
to retrieve thestart_time
.Try This query.