I Have a table that looks like this:
Table1
:
Time_stamp bigint, << Notice this is bigint and not timestamp, so this needs to be casted
amount int,
name_ev text,
badge_number int,
type text
(We only want to pull information for rows where the type
is in ('customer', 'client')
)
And another table that looks like this:
Table2
:
timestamp TIMESTAMP,
low int,
high int
(This is by the minute, so every minute has a value low, high)
and a third table that looks like this:
Table3
:
name text,
badge_number text, << Notice this is text and not int, so this needs to be casted
trip_data
(There can only exist one name, and one badge_number, meaning no dupes here)
I'm attempting to pull this:
timestamp, name, badge_number, highest_Day, lowest_Day, highest_Week, lowest_Week, highest_Month, lowest_Month, trip_data, amount_day, amount_week, amount_month, badge_day, badge_week, badge_month, last_trip_amount, last_trip_time_stamp
Explentation:
Explentation:
timestamp
: The time_stamp fromTable1
name
: thename
fromTable1
badge_number
: thebadge_number
fromTable1
highest_Day
: a the highest value ofhigh
inTable2
WhereTable2.timestamp
is betweenTable1.time_stamp - 1 Day
andTable1.time_stamp
lowest_Day
: a the highest value oflow
inTable2
WhereTable2.timestamp
is betweenTable1.time_stamp - 1 Day
andTable1.time_stamp
- (The same for Week/Month but instead of Day, it's 1 Week (7 days), and 1 Month (30 Days))...
trip_data
: the value oftrip_data
fromTable3
whereTable3.name
matchesTable1.name_ev
andTable3.badge_number
matchesTable1_badge_number
amount_day
: the sum ofamount
fromTable1
for all objects whereTable1.time_stamp
is betweenTable1.time_stamp - 1 Day
andTable1.time_stamp
- (The same for Week/Month but instead of Day, it's 1 Week (7 days), and 1 Month (30 Days))...
badge_day
: is the same as amount_day, but only whereTable1.badge_number
matchesTable1.badge_number
andTable1.time_stamp
is betweenTable1.time_stamp - 1 Day
andTable1.time_stamp
- (The same for Week/Month but instead of Day, it's 1 Week (7 days), and 1 Month (30 Days))...
last_trip_amount
: is the value ofTable1.amount
whereTable1.name_ev
andTable1.badge_number
match the recordsname_ev
andbadge_number
last_trip_time_stamp
: is the same as above, but instead of amount it's the timestamp.
Note that Table1
is not sorted, and should be sorted on timestamp when retrieving the last object (ie sort by time_stamp desc limit 1) or whatever.
The goal is to pass a badge_number
and return all records (ie ~15k) in the above response.
CodePudding user response:
Use WITH clauses to split the Big query into several smaller ones, which you can name. Each sub-query will be executed only once, and performance shouldn't be a problem.