I have a table (Oracle SQL) containing details of a list of item prices at each store location. I want to combine several rows into one -- but only when ALL rows for an item meet the criteria: the item is the same price at all locations.
The data table (simplified) looks like this:
list_id, item_id, location_id, item_price
1 1 1 1.99
1 1 2 1.99
1 1 3 1.99
1 2 1 3.99
1 2 2 3.99
1 2 3 3.99
1 3 1 5.99
1 3 2 7.99
1 3 3 8.99
...and I want this:
list_id, item_id, location_id, item_price
1 1 0 1.99
1 2 0 3.99
1 3 1 5.99
1 3 2 7.99
1 3 3 8.99
Rows for items 1 and 2 have been combined into a single row each, with location set to zero(all). Rows for item 3 have remained unchanged because the price was not the same in ALL locations.
This query helps me to identify when an item doesn't need to be merged (two rows exist with the same item_id):
select count(list_id), item_id, item_price
from list_detail
group by item_id, item_price
...but I can't wrap my head around how it would fit into a larger trigger, script, or whatever which would identify and combine rows.
NOTE: I cannot change the structure of the table because it is relied on by many, many other processes.
How would you best identify and then combine rows where the price is the same in all locations? A script, trigger, scheduled console app?