scubadude :
I am working on sql queries in woocommerce and wordpress where I have three tables that need to join as a query result. Basically, I'd like to list delivery date with total item that needs on that day across multiple order id. Here is what the table looks like:
TABLE_A
| id | order_id | date |
| 1 | 20 | 2020-04-12 00:00:00 |
| 2 | 21 | 2020-04-14 00:00:00 |
| 3 | 22 | 2020-04-14 00:00:00 |
TABLE_B
| order_item_id | order_item_name | order_id |
| 50 | Item A | 20 |
| 51 | Item B | 20 |
| 52 | Item C | 21 |
| 53 | Item A | 21 |
| 54 | Item A | 22 |
TABLE_C
| detail_id | order_item_id | key | Value |
| 1 | 50 | qty | 2 |
| 2 | 51 | qty | 3 |
| 3 | 52 | qty | 3 |
| 4 | 53 | qty | 4 |
| 5 | 54 | qty | 2 |
Desired Outcome
| date | order_item_name | total |
| 2020-04-12 00:00:00 | Item A | 2 |
| 2020-04-12 00:00:00 | Item B | 3 |
| 2020-04-14 00:00:00 | Item C | 3 |
| 2020-04-14 00:00:00 | Item A | 6 |
What i did:
SELECT
date,
order_item_name,
sum(value) as Total
FROM
TABLE_A
INNER JOIN TABLE_B USING (order_id)
INNER JOIN TABLE_C USING (order_item_id)
GROUP BY order_item_id
But i cant seem to get the total correct, any help will be much appreciated, thank you
Mansi :
SELECT
date,
order_item_name,
sum(value) as Total
FROM
TABLE_A
INNER JOIN TABLE_B USING (order_id)
INNER JOIN TABLE_C USING (order_item_id)
GROUP BY order_item_name,date
ORDER BY order_id ASC
Since you need the items date wise, group by needs to be performed on item name and date. This query will fetch the desired result.
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=402178&siteId=1