I have a following table :
prod_name - quantity - group
tv - 30 - base
microwave - 10 - base
watch - 5 - base
phone - 25 - base
washer - 15 - base
dryer. - 14 - base
microwave - 7 - inventory_2021
phone - 16 - inventory_2021
tv - 30 - inventory_2022
watch - 5 - inventory_2022
phone - 25 - inventory_2022
I want to fill/ enter missing records from base(group) to all other groups
Expected output :
tv - 30 - base
microwave - 10 - base
watch - 5 - base
phone - 25 - base
washer - 15 - base
dryer. - 14 - base
tv - 30 - inventory_2021
microwave - 7 - inventory_2021
watch - 5 - inventory_2021
phone - 16 - inventory_2021
washer - 15 - inventory_2021
dryer. - 14 - inventory_2021
tv - 30 - inventory_2022
microwave - 10 - inventory_2022
watch - 5 - inventory_2022
phone - 25 - inventory_2022
washer - 15 - inventory_2022
dryer. - 14 - inventory_2022
So in the output I have same number of entries in each group and total number of entries should match the base group.
2
Answers
Use
CROSS JOIN
to create all the missing rows. Then you canLEFT JOIN
this with the original table to fill in the gaps.DEMO
MySQL and Presto/Trino are two a bit SQL different dialects. The basic idea is the same – build the "base" cartesian product of products and groups. If you are sure that all products are present in base you can go simply with the following for Presto/Trino:
Output: