I have a bigquery table in format company_id, date, sales_amount. sales_amount is a FLOAT64 column which value can vary from 0 to 1 Billion. I need to find the first date for every company_id a particular sales_amount range hit for the first time.
What I have written so far is for each range a with clause is used for example :
With A as (
SELECT company_id, min(date) breakDate
FROM <table>
WHERE sales_amount >= 100000 and sales_amount < 500000
GROUP BY company_id
),
B as (
SELECT company_id, min(date) breakDate
FROM <table>
WHERE sales_amount >= 500000 and sales_amount < 1000000
GROUP BY company_id
),
AllUnion AS (
SELECT * FROM A
LEFT JOIN B
USING(company_id)
WHERE B.breakDate > A.breakDate OR B.company_id is NULL
UNION ALL
SELECT * FROM B
)
So when a new range is added I have to add a new With section and in the last a big union section to merge all the break events. In the merge time I will make sure that if Higher order events happend first then lower order events are filtered out. For example in this case a company made more than 500K sales in Jan (First time) and their sales went down and hit 120K in Feb. Only 500K sales event will be returned Feb event will be filtered out
I have to do it for different tables and might have more events, I am wondering is there a smart way to write this query in bigquery ?