I have 2 tables
orders
order_id |
---|
1 |
2 |
3 |
orders_details
order_id | sku | ordered | received |
---|---|---|---|
1 | abc | 10 | 10 |
1 | xyz | 10 | 10 |
2 | abc | 10 | 6 |
2 | xyz | 10 | 0 |
3 | abc | 10 | 0 |
4 | xyz | 10 | 0 |
I would like to add to the orders table a column called status which would have the results ‘complete’, ‘partial’ and ‘open’ based on what has been received in the orders_details table
result I am trying to acheive
order_id | status |
---|---|
1 | complete |
2 | partial |
3 | open |
The problem is when a different product from the same order_id has a different received result it creates an additional row with the group by.
result I am getting
order_id | status |
---|---|
1 | complete |
2 | open |
2 | partial |
3 | open |
https://www.db-fiddle.com/f/bFrYguhmcMJ32iFuUcXfDw/3
SELECT
`orders`.`order_id`,
(CASE
WHEN `received` >= `ordered` THEN 'complete'
WHEN `received` < `ordered` AND `received` != 0 THEN 'partial'
WHEN `received` = 0 THEN 'open'
END) AS `status`
FROM
`orders`
LEFT JOIN `orders_details` ON `orders_details`.`order_id` = `orders`.`order_id`
GROUP BY
`order_id`, `status`
;
2
Answers
It is a bit hacky, but you can define the order by giving then names of the status an order the should be choosen, and then take the maximum for this order.
We can thenremove the additional charatcers
Query #1
View on DB Fiddle
I might be missing something, but I think you just want:
Here’s your updated DB Fiddle