Last Month to Date - sql

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()

Related

Previous year Year To Date with partial current year Year To Date Calculation SQL Server

I have a revenue table with data for last year and current year. I need to calculate the YTD last year and YTD current year, BUT I need to only consider data from min(date) from last year PER branch for current year YTD calculation.
eg: Branch KTM has data from 2018-02-25 not from Jan 1st.
Now I want to get YTD for the current year from the same date on 2019 till today.
I am able to get whole YTD for last year and this year, and also the minimum date/weeknumber for each branch for last year, but unable to calculated partial YTD for the current year.
Here is one drive link to mydata and sql : https://1drv.ms/u/s!Ave_-9o8DQVEgRS7FaJmm48UNsWz?e=lRfOJF
A snippet from my code
I need help with the SQL query to do this.
This returns the number of days between the same day-of-year of a last year's date and today's date:
select current_date - (date'2018-02-25' + interval '1' year); -- PostgreSQL
select datediff(current_date, (date'2018-02-25' + interval '1' year)); -- MySQL
Alternative version:
select extract(doy from current_date) - extract(doy from date'2018-02-25'); -- PostgreSQL
doy stands for day of year. At the time of the answer (2019-09-24) all queries return 211.
To sum values in that date range, use BETWEEN:
SELECT sum(revenue)
FROM your_table
WHERE date BETWEEN date'2018-02-25' + interval '1' year AND current_date

How to decipher complex DATEADD function from MS Access

I have inherited a query from an old MS Access DB and cannot for the life of me figure out what was trying to be done in this date parameter function. I normally only use SQL and this seems a bit different. Can any one assist in describing what this logic is doing?
use pdx_sap_user
go
select po_number,
po_issue_date
from vw_po_header
where po_issue_date > getDate() And PO_issue_date < DateAdd("d",-1,DateAdd("m",8,DateAdd("d",-(Day(getDate())-1),getDate())))
You can de-obfuscate it a lot by using DateSerial:
where
po_issue_date > getDate() And
po_issue_date < DateSerial(Year(getDate()), Month(getDate()) + 8, 0)
First: there is no getDate() function in Access. Probably it should be Date() which returns the current date.
Now starting from the inner expression:
Day(Date()) returns the current day as an integer 1-31.
So in DateAdd("d", -(Day(Date())-1), Date()) from the current date are subtracted as many days as needed to return the 1st of the current month.
Then:
DateAdd("m", 8, DateAdd("d", -(Day(Date())-1), Date()))
adds 8 months to the the 1st of the current month returning the 1st of the month of the date after 8 months.
Finally:
DateAdd("d", -1,...)
subtracts 1 day from the date returned by the previous expression, returning the last day of the previous month of that date.
So if you run today 13-Sep-2019 this code, the result will be:
30-Apr-2020
because this is the last day of the previous month after 8 months.
I think the following:
Take the current date
Substract the current day of month -1 to get the first day of current month
Add 8 month to this
Substract 1 day to get the last day of the previous month
So it calculates some deadline in approx 8 months.
But I wonder how a PO issue date can be in the future...

BigQuery using MAX() function

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

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]

SSRS BIDS 2008 Expression

What is the correct expression to use for todays date plus 1 year.
I assume it starts with Now()+ but im unsure from there
This page has lots of great examples, including:
=DateAdd(DateInterval.Month, 6, Parameters!StartDate.Value)
From that and the example before it, it looks like you want:
=DateAdd(DateInterval.Year, 1, Today())
this should be what your looking for:
--midnight last day of last month
select DateAdd(mm,-0,(DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))))
--midnight last day of this month
select DateAdd(mm,+1,(DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))))
--midnight last day of last month 1 year ago
select DateAdd(yy,-1,(DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))))
--midnight last day of this month 1 year ago
select DateAdd(yy,-1,DateAdd(mm,+1,(DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)))))