I have a complicated problem that needs to be solved in t-sql. Possibly without a cursor or a loop.
Given the following table with customer’s payment setup.
ID Frequency Amount Start Date End Date
1 Monthly 100 01-01-2016 N/A(ongoing)
The customer wants to know how much he\she will have to pay for the month of November.
If they were to close the account on 15 nov 2016.
For example:
Assume the customer wants to close their account on 15-nov-2016 and wants to know the $amount they will be paying from 1st of November to 15 of November.
Calculation
The frequency cycle for the customer payment is Monthly.
Taking the frequency into account we know that:
Customer start date of November will be 1st of November
The end date will be 30 November
Calculation formula
(DayUpToCloseDate/DaysInNov) * Amount = amount customer is asking.
DaysUpToCloseDate = 15 (diff 1st of nov and 15th of nov)
DaysInNov = 30
Amount = 100
(15/30)*100 = 50
So we can tell the customer he/she will be paying 50$ in November if they were to close the account on 15th of November.
First we need to declare the 2 variables, the date in question and the monthly amount due.
DECLARE #date datetime = '2017-11-15'
DECLARE #amountDue int = 100
Then to get the month to date amount due we can use:
SELECT CAST(DATEPART(DAY,#date) AS FLOAT)/DATEPART(DAY,DATEADD(MONTH,DATEDIFF(MONTH,0,#date)+1,0)-1) * #amountDue AS [MonthToDateAmountDue]
Here is how we got there.
SELECT
--This gets the first day of the next month and subtracts 1 day, getting the last day of the month the date falls in.
DATEADD(MONTH,DATEDIFF(MONTH,0,#date)+1,0)-1 AS [LastDayOfMonth]
--We now extract the day date part of the last day of the month to get the total days in the month.
,DATEPART(DAY,DATEADD(MONTH,DATEDIFF(MONTH,0,#date)+1,0)-1) AS [DaysInMonth]
--Finally, we get the day date part from our #date and divide by the total days of the month to get the percentage of the month we have completed.
--Since int does not do decimals, we use a float.
,CAST(DATEPART(DAY,#date) AS FLOAT)/DATEPART(DAY,DATEADD(MONTH,DATEDIFF(MONTH,0,#date)+1,0)-1) AS [PercentageOfMonthCompleted]
--And mulitply it by the amount due.
,CAST(DATEPART(DAY,#date) AS FLOAT)/DATEPART(DAY,DATEADD(MONTH,DATEDIFF(MONTH,0,#date)+1,0)-1) * #amountDue AS [MonthToDateAmountDue]
Edit: So, I just learned about the EOMONTH function. This can be shortened to
SELECT CAST(DATEPART(DAY,#date) AS FLOAT)/DATEPART(DAY,EOMONTH(#date)) * #amountDue AS AS [MonthToDateAmountDue]
Related
I have a table with the sales from last 2 years, and I want to compare the sales from this year with the same natural day last year. For example, Sunday 1st of April 2018 will be compared with Sunday 2nd April 2017.
In order to do that I have created the measure
sales_last_year = CALCULATE(Sales[Revenue]); SAMEPERIODLASTYEAR(DATEADD('Calendar'[Date];+1;DAY)))
And I have created another measure where I have the value from the same day last year:
Prueba_sales_last_year = CALCULATE(Sales[Revenue]); SAMEPERIODLASTYEAR('Calendar'[Date]))
The result is the following:
Sales last year
As you can see the sales per day shows 5.316€ and 3.546€, which is correct, but the total is 111.796 €, which is not correct. However, the measure with the formula without the natural day the sum of the two rows is correct. How could I solve this?
Thank you very much in advance
I just changed the order to calculate the date and it was solved.
sales_last_year = CALCULATE(Sales[Revenue]);DATEADD( SAMEPERIODLASTYEAR('Calendar'[Date]);+1;DAY))
I am trying to produce a query in SQLite where I can determine the average sales made each weekday in the year.
As an example, I'd say like to say
"The average sales for Monday are $400.50 in 2017"
I have a sales table - each row represents a sale you made. You can have multiple sales for the same day. Columns that would be of interest here:
Id, SalesTotal, DayCreated, MonthCreated, YearCreated, CreationDate, PeriodOfTheDay
Day/Month/Year are integers that represent the day/month/year of the week. DateCreated is a unix timestamp that represents the date/time it was created too (and is obviously equal to day/month/year).
PeriodOfTheDay is 0, or 1 (day, or night). You can have multiple records for a given day (typically you can have at most 2 but some people like to add all of their sales in individually, so you could have 5 or more for a day).
Where I am stuck
Because you can have two records on the same day (i.e. a day sales, and a night sales, or multiple of each) I can't just group by day of the week (i.e. group all records by Saturday).
This is because the number of sales you made does not equal the number of days you worked (i.e. I could have worked 10 saturdays, but had 30 sales, so grouping by 'saturday' would produce 30 sales since 30 records exist for saturday (some just happen to share the same day)
Furthermore, if I group by daycreated,monthcreated,yearcreated it works in the sense it produces x rows (where x is the number of days you worked) however that now means I need to return this resultset to the back end and do a row count. I'd rather do this in the query so I can take the sales and divide it by the number of days you worked.
Would anyone be able to assist?
Thanks!
UPDATE
I think I got it - I would love someone to tell me if I'm right:
SELECT COUNT(DISTINCT CAST(( julianday((datetime(CreationDate / 1000, 'unixepoch', 'localtime'))) ) / 7 AS INT))
FROM Sales
WHERE strftime('%w', datetime(CreationDate / 1000, 'unixepoch'), 'localtime') = '6'
AND YearCreated = 2017
This would produce the number for saturday, and then I'd just put this in as an inner query, dividing the sale total by this number of days.
Buddy,
You can group your query by getting the day of week and week number of day created or creation date.
In MSSQL
DATEPART(WEEK,'2017-08-14') // Will give you week 33
DATEPART(WEEKDAY,'2017-08-14') // Will give you day 2
In MYSQL
WEEK('2017-08-14') // Will give you week 33
DAYOFWEEK('2017-08-14') // Will give you day 2
See this figures..
Day of Week
1-Sunday, 2- Monday, 3-Tuesday, 4-Wednesday, 5-Thursday, 6-Saturday
Week Number
1 - 53 Weeks in a year
This will be the key so that you will have a separate Saturday's in every month.
Hope this can help in building your query.
I have a table in a data model that has forecast figures for the next 3 months. What I want to do is to show what the forecast number for the current month to date is.
When I use the DATESMTD function like this:
=CALCULATE(SUM(InternetSales_USD[SalesAmount_USD]),DATESMTD(DateTime[DateKey]))
I get the last month of my data summarised as a total. I assume that is because the DATESMTD function takes the last date in the column and that is 3 months away.
How do I make sure I get this current month MTD total rather then the end of the calendar? The formula should be clever enough to realise I am in May and want the May MTD not the August MTD.
Any ideas?
The way to do this is to do this:
Forecast_Transaction_MTD:=CALCULATE(sum('ATO Online'[2017 Transaction Forecast]), DATESINPERIOD('ATO Online'[Current Year],TODAY(),-day(TODAY()),day))
the last -day(TODAY()) gets the day number for the current day and subtract it from today's date. So, today is the 25 May. the -day(TODAY())),day)) extracts the day (25) and subtracts it from the current date to get me to the 1 May.
The rest of the formula just adds the total for the dates.
I am trying to create a query than can calculate the number of days, in a given month, that a particular stock item was unavailable (ie: No. = 0).
Currently, I have developed a query that can calculate the number of days it has been from today's date where stock has been unavailable but what I am trying to actually calculate is, during a month, how many days was stock quantity = 0. ie: Month of Jan - on Jan 5, Jan 7 and Jan 20 there was no stock for Item A - this means that the number of days out of stock was = 3.
Extra Details:
Currently, I am basing my query in determining stock levels of the last transaction (ie: if, at the last transaction, the QTY of Stock = 0) then calculate the number of days between the transaction date and today.
Select [StockItems].StockCode,
Case When SUM([StockItems].Qty_On_Hand)=0 Then (Datediff(day, GETDATE(),MAX([Transactions].TransactionDate))) ELSE 0 END AS 'Days Out of Stock',
From dbo.[Transactions]
INNER JOIN [StockItems]
ON [Transactions].[AccountLink] = [StockItems].[StockLink]
Where [StockItems].StockCode LIKE '%XXX%'
AND [Transactions].TransactionDate>31/10/14
Group By [StockItems].StockCode
My Thoughts
There are different sorts of transactions - one of which is a good received transaction. Perhaps it is possible to calculate the days where Stock Qty was zero and a transaction occurred then count that date until goods were received.
Thoughts?
Thank You.
SELECT COUNT([StockItems].Qty_On_Hand
From dbo.[Transactions]
INNER JOIN [StockItems] ON [Transactions].[AccountLink] = [StockItems].[StockLink]
WHERE [StockItems].Qty_On_Hand)=0
How do I write query if I want 1st day of the month falls in 1st week. my report needs to show data from SUN-SAT.so,
if I run the report on anyway current week, it should only show the data for the previous week from SUN-Sat.
Even though 10/27 falls in the 5th week of October , I am required to show as 10/27- 11/02 falls in the first week of November since November 1 falls in the first
week of November.
Here it is how I want to display the date-range in my report for the month of November. and the same logic applies
for every month.
Week 1 10/27 to 11/02
Week 2 11/03 to 11/09
Week 3 11/10 to 11/16
Week 4 11/17 to 11/23
Week 5 11/24 to 11/30
so, I am not counting till 4th week of October not the 5th one because I am counting 5th week as week 1 for
November.
like wise, the first week of JAN will be 12/29 till 01/04 . I don't want to count 5th week of December because if
I count, there will be duplication.
Thank you. I appreciate it.
In simpler terms, an entire week 'belongs' to a specific month based on whatever month the Saturday of that week lies in. Then you want to work backwards and calculate for a given month, the set of all weeks that belong to that month.
This will give you the forward calculation:
declare #date date = getdate();
select month(dateadd(day,7+datediff(day,#date,'2000-01-01')%7,#date))
And the reverse calculation:
declare #year int = 2013
declare #month int = 11
select
datefromparts(#year,#month,1) as month,
dateadd(day,i*7+datediff(day,datefromparts(#year,#month,1),'2000-01-01')%7-6,datefromparts(#year,#month,1)) week_start,
dateadd(day,i*7+datediff(day,datefromparts(#year,#month,1),'2000-01-01')%7 ,datefromparts(#year,#month,1)) week_end
from (values(1),(2),(3),(4),(5)) wk(i)
I use datediff(day,#date,#known_date) instead of datepart(dw,#date) because it is deterministic.