BigQuery using MAX() function - sql

So I have a query in BQ that looks as such:
SELECT
SubscriptionId,
start_time,
STRFTIME_UTC_USEC((UTC_USEC_TO_MONTH(TIMESTAMP_TO_USEC(TIMESTAMP(start_time)))),'%B %Y') AS cohort_month,
UTC_USEC_TO_MONTH(start_time) AS usec_month,
STRFTIME_UTC_USEC((UTC_USEC_TO_WEEK(TIMESTAMP_TO_USEC(TIMESTAMP(start_time)), 0)),'%Y-%m-%d') AS cohort_week,
WEEK(start_time) AS usec_week,
DATE(start_time) AS cohort_day,
UTC_USEC_TO_DAY(start_time) AS usec_day,
amount,
current_period_start,
current_period_end,
cancel_date,
end_date,
cancel_at_period_end,
salesRepEmail,
CASE WHEN (salesRepEmail IS NOT NULL) THEN 'Telesales' ELSE 'Online' END AS sales_channel,
status,
type_id,
CASE WHEN (type_id IN ('150032',
'150033',
'150023')) THEN 'Annual' ELSE 'Monthly' END AS duration,
refunded
FROM
[data_snapshots_daily.subs_charges_refunds_]
WHERE
start_time >= '2016-04-01 00:00:00'
AND refunded = FALSE
What I'm looking to do though, is add on to the query so that it returns all the relevant data from the most recent month, week, and day.
So I imagine it involves something to do with MAX(usec_month) but I can't figure it out. Remember, I only want it to return relevant data when it's included in the most recent month (June)

i think of something like below
for current month
WHERE YEAR(CURRENT_DATE()) = YEAR(start_time)
AND MONTH(CURRENT_DATE()) = MONTH(start_time)
for current week
WHERE YEAR(CURRENT_DATE()) = YEAR(start_time)
AND WEEK(CURRENT_DATE()) = WEEK(start_time)
for current day
WHERE CURRENT_DATE() = DATE(start_time)
quick add
for last two weeks play with something like below (should be improved to handle first week of the year)
WHERE (YEAR(CURRENT_DATE()) = YEAR(start_time) AND WEEK(CURRENT_DATE()) = WEEK(start_time))
OR CASE WHEN WEEK(CURRENT_DATE()) = 1
THEN (YEAR(CURRENT_DATE()) - 1 = YEAR(start_time) AND 53 = WEEK(start_time))
ELSE (YEAR(CURRENT_DATE()) = YEAR(start_time) AND WEEK(CURRENT_DATE()) - 1 = WEEK(start_time))
END
Breakdown of above statement (per your request)
It looks for starttime that either belong to current or previous week. Current week is straightforward. In case of previous week it looks if current week is not the first week of the year - in this case condition is - same year but previous week. And in case if current week is first week of the year - it looks for last week of previous year.
cleaner version to handle last two weeks condition
DATE(start_time)>DATE(DATE_ADD(CURRENT_DATE(),-7*1-DAYOFWEEK(CURRENT_DATE()),'DAY'))
changing 1 in 7*1 to let's say 3 - will give you condition for last four weeks for example

Related

Previous Month Function - Big Query

For example : today = '2022-04-18'
I need previous month date function. İt is march month.
= '2022-03-01' - '2022-03-31'

Last Month to Date

I am trying to calculate the sales for last month to date.
I have created the month to date as the following:
sum(case when year(s.bus_dat) = year(getdate()) and month(s.bus_dat) = month(getdate())
then qty_sold end) as MTD_SAL,
I need to create the last month to date in a similar way (I want the code represent the date from the beginning of last month til today so if today is 10/28/2018 I need to show all the sales from 09/01/2018 to 10/28/2018
Any advice please?
Calculate the first day of the month, then go back a month using this:
dateadd(m,-1,dateadd(d,-day(getdate())+1,getdate()))
Need to make sure its the start of the day, so convert to date:
convert(date,dateadd(m,-1,dateadd(d,-day(getdate())+1,getdate())))
So your complete columns becomes:
sum(case when s.bus_dat>=
convert(date,dateadd(m,-1,dateadd(d,-day(getdate())+1,getdate()))))
then qty_sold else 0 end) as LM
To get something between last month and today you can use :
BETWEEN DATE(CONCAT(YEAR(NOW()),'-',MONTH(NOW()),'-01')) - INTERVAL 1 MONTH AND DATE()

SQL code for CUrrent Month Last Year

I am using the dataadd function trying to find the sum where a certain date field is in the current month but of the previous year.
sum(case when (mt04 >= DATEADD(MONTH,-12,getdate()) and (mt04 <= dateadd(month,-11,getdate())))
then 1 else 0
end) as [New Instructions Same Month Last Year],
This is the report I am using and at the moment it is showing the data from this point onwards to the end of the month. E.g. if I ran it on the 8th of the month it is showing data from 8th onwards of the current month of the previous year. I need a total for the whole month of the previous year.
Because this is in a sum(), there is no advantage to putting all the function calls on the current date. So, just use month() and year():
sum(case when year(mt04) = year(getdate()) - 1 and month(mt04) = month(getdate())
then 1 else 0
end) as [New Instructions Same Month Last Year]

How to pull previous month data for in January

I have an embedded query that I use to pull previous month data. Everything has been working fine until this month (January). My code looks like this:
(MONTH(CURRENT DATE)-1) = MONTH(TSTAMP)
I have it setup this way because I have a timestamp in my data that I base the query off of. This usually works like a charm, but it's not working this month and I think it's because of the new year. How does this function work when dealing with a different year? Is there a way to write it into the query so I don't have to worry about a change in year?
You can do this by using the year, like this:
YEAR(CURRENT DATE) * 12 + MONTH(CURRENT DATE) - 1 = YEAR(TSTAMP) * 12 + MONTH(TSTAMP)
This, in essence, converts the dates into months since time 0 -- so the -1 makes sense.
The proper way to do this is with a range query (one with an exclusive upper-bound, <, too), so that the db is free to us an index if one is available.
The first of the month can be retrieved pretty easily via:
CURRENT_DATE - (DAY(CURRENT_DATE) - 1) DAYS
(Subtract the difference in days between the current date and the start of the month)
This gives a wonderful upper-bound condition for the query:
WHERE tStamp < CURRENT_DATE - (DAY(CURRENT_DATE) - 1) DAYS
(Get everything before the start of the current month).
However, since we're really only interested in the previous month, we also need to limit the lower bound. Well that's everything since, or on, the start of that month... and since we can already get the start of the current month:
WHERE tStamp >= CURRENT_DATE - (DAY(CURRENT_DATE) - 1) DAYS + 1 MONTH
AND tStamp < CURRENT_DATE - (DAY(CURRENT_DATE) - 1) DAYS
There's a related way to do this, supposing you have a calendar table with appropriate indices. If you have a minimal table with these columns:
calendarDate - DATE
year - INTEGER
month - INTEGER
dayOfMonth - INTEGER
... you can use this table to get the relevant values instead:
WHERE tStamp >= (SELECT calendarDate
FROM calendarTable
WHERE year = YEAR(CURRENT_DATE - 1 MONTH)
AND month = MONTH(CURRENT_DATE - 1 MONTH)
AND dayOfMonth = 1)
AND tStamp < (SELECT calendarDate
FROM calendarTable
WHERE year = YEAR(CURRENT_DATE)
AND month = MONTH(CURRENT_DATE)
AND dayOfMonth = 1)
(there's a couple of different forms of this, but this one looks pretty simple)

Date formatting sql plus

I have this sql script:
select 'LASTBUSDATE='|| to_char(max(calen_dt),'mmdd') LBD
from put_calen
where calen_dt < (select calen_dt from put_calen where ca_run_dt_ind = 'Y')
and business_day_ind = 'Y';
exit;
How can I modify this so I will get first business day and last business day of previous month like 2-1-2011 and 2-28-2011
Please help. Don't know whats going on in here.
I'm guessing on your table structure from your column names here, but does the following return what you want?
select min(calen_dt) as first_business_day
,max(calen_dt) as last_business_day
from put_calen
where calen_dt >= trunc(sysdate,'MM') - interval '1' month
and calen_dt <= trunc(sysdate,'MM') - interval '1' day
and business_day_ind = 'Y';
If sysdate = "2011-03-31 19:14:32", then trunc(sysdate,'MM') would return "2011-03-01 00:00:00"; basically the date truncated to month.
You wanted the first and last business day in previous month, so I subtracted 1 month to arrive at the first of the previous month, and 1 day to arrive at the last day of the previous month. The filter business_day_ind = 'Y' makes sure that only business days are consider for the min/max.
Let me know how it works, or if I missunderstood your question and/or table structure :)