Skip to content
Advertisement

SQL: Filling in Missing Records with Conditional

I need to count the number of products that existed in inventory by date. In the database however, a product is only recorded when it was viewed by a consumer.

For example consider this basic table structure:

Using the following query, I attempt to determine the amount of products in inventory on a given date.

This is the output

My output is not an accurate reflection of how many products were in inventory due to missing rows.

The correct understanding of inventory is as follows:
– Product A was present in inventory from July 1 – July 10.
– Product B was present in inventory from July 2 – July 4.
– Product C was in inventory from July 4 – July 5.

The correct SQL output should be:

If you are following along, let me confirm that I am comfortable defining “in inventory” as the date difference between the first & last view.

I have followed the following faulty process:

First I created a table which was the cartesian product of every productID & every date. ”’ with Dates as ( select date from SomeTable group by date ), Products as ( select productId from SomeTable group by productId ) select Dates.date, Products.productId from Dates cross join Products ”’

Then I attempted do a right outer join to reduce this to just the missing records:

Then with the missing rows in hand, union them back onto the Records. in doing so, I create a new problem: extra rows.

And when I run my simple query select date, count(distinct productId) as Inventory, sum(views) as views on that table I get the wrong output again:

My next thought would be to iterate through each productId, determine it’s first & last date, then Union that with the Cartesian table with the condition that the Cartesian.date falls between the first & last date for each specific product.
There’s got to be an easier way to do this. Thanks.

Advertisement

Answer

Below is for BigQuery Standard SQL

If to apply to sample data from your question as in below example

result is

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement