I’ve got a tricky SQL problem. There’s this table with fruit sales data. It has columns for fruit type, quantity, total, and time. Some rows have null values. I need to replace these nulls with the most recent non-null data for each fruit type.
Here’s a simplified example of what I’m after:
CREATE TABLE fruit_sales (
fruit_type VARCHAR(10),
quantity INT,
total INT,
sale_time TIME
);
INSERT INTO fruit_sales VALUES
(NULL, NULL, NULL, '08:00:00'),
('banana', 3, 3, '08:30:00'),
(NULL, NULL, NULL, '09:00:00'),
('apple', 5, 5, '09:30:00');
I want a query that fills in the nulls like this:
SELECT
COALESCE(fruit_type, 'unknown') AS fruit_type,
COALESCE(quantity, 0) AS quantity,
COALESCE(total, 0) AS total,
sale_time
FROM
-- Some magic SQL here
;
This should give me rows for each fruit type at every time point, using the last known values. Any ideas on how to tackle this? I’m stumped!