Excel MDX - same period last month - totals - sql

I have the following MDX expression which helps me to display the data for the 'same period last month' from the Cube PER DAY.
Filter(
[Date].[Date].[Date],
[Date].[Date].CurrentMember.Member_Value >=
DateSerial(Year(DateAdd('m', -1, VBA![Date]())),
Month(DateAdd('m', -1, VBA![Date]())),
1
)
AND [Date].[Date].CurrentMember.Member_Value < DateAdd('m', -1, VBA![Date]())
)
Now I would like to redo the code to display just the total for this period without breaking it down per day. The reason for this is, that if for example I want to see the total number of active users for the same period last month I can't simply sum up the numbers of daily users as this will be higher than the real number of total users in this period (user may be active on more than one day and I just want to count him once for this period).
I tried chaning the code but nothing works so far. Any ideas?
Many thanks in advance,
Maciej

Related

SQL - Count month difference in non-consecutive date period

I am trying to extract how many months of membership a member gets up to date. As the picture shows, this member got four years of subscription since 2018. However, she stopped the subscription for a year ending in 2019. And then, restart the membership in 2020 again.
Each membership lasts for 12 months. if we look at the last membership starting from 2022-05-08, it will end up on 2023-05-08. However, I only want to get the total month count up to date(getdate - 2022-09-14).
Please advise how I could approach this matter. Thanks!
enter image description here
Assuming you were planning to apply sum(monthcount), you could wrap the monthcount within a CASE statement to checks if the vip_end is greater than today's date:
sum(case when vip_end > getdate() then ... else monthcount end)
What you do within that ... depends on whether you wanted to just count the different number of months within the date range (e.g. 31st Jan -> 01st Feb is counted as a whole month because it just considers Jan -> Feb):
datediff(month, datecreated, getdate())
or perhaps calculate the number of months based on the average days in a month:
datediff(day, datecreated, getdate())*12.0/365.25
or maybe something else... it really depends on what level of detail you want to achieve.

Calculating a parameter dynamically based on the input in SQL Server stored procedure

I need to write a SQL Server stored procedure where based on the input date given by the user, data needs to be calculated dynamically.
To explain in detail, I need to find the sum of weights recorded from start of a month till the input date in the database.
The data will be recorded in DB during each shift for each day.
A day consists of 3 shifts. So number of shifts will be 3*30=90 (for a 30 days month).
Here is where it gets tricky. My query needs to be such that, the number of shifts should be calculated dynamically based on the input date.
For example, if the input date is 20, then no.of shifts will be 3*20=60 (from 1st day of the month to input day).
This number of shifts will be used to calculate the total average weight recorded for that month.
[Sum of weights from 1st day till input day]
/ [no. of shifts from first day of month till input day]
I am providing part of my stored procedure that is relevant to this question. I can find the number of days from start date to input date, but I am unable to calculate the number of shifts based on the input date.
#Reportdate DATETIME,
SELECT
PartName,
(SUM((COALESCE(weightActualPerCent, 0))) / 'total shifts') AS 'OverWeight%'
FROM
table1
WHERE
Process = 'Cooling'
AND Day >= DATEADD(MONTH, DATEDIFF(MONTH, 0, #Reportdate), 0)
AND Day < #Reportdate;
In the above code, the denominator 'total shifts' should be calculated dynamically based on the number of days between start date and input date. Any suggestions/pointers will be much appreciated.
Apologies if the question was too lengthy or confusing.

Sum values on date table where one column equals a selected value from another

I have a DimDate table that has a Billable Day Portion field that can be between 0 and 1. For each day that's in the current Bonus Period I want to multiple that Day Portion by 10, and then return the total sum.
To find out what Bonus Period we're in, I return ContinuousBonusPeriod where the date equals today:
Current Continuous Bonus Period:= CALCULATE(MAX(DimDate[ContinuousBonusPeriod]), FILTER(DimDate, DimDate[DateKey] = TODAY()))
I can see in the measure display this is correctly coming back as Bonus Period 1. However, when I then use ContinuousBonusPeriod in the measure to determine the number of days in the current period, it only returns 10, 1 day multiplied by the static 10.
Billable Hours This Period:= CALCULATE(SUMX(DimDate, DimDate[Billable Day Portion] * 10), FILTER(DimDate, DimDate[ContinuousBonusPeriod] = [Current Continuous Bonus Period]))
It appears to be only counting today's DimDate record instead of all the records whereContinuousBonusPeriod = 'Bonus Period 1' as I'd expect.
I needed to make sure no existing filter was applied to the DimDate table when calculating the Current Continuous Bonus Period:
Current Continuous Bonus Period:= CALCULATE(MAX(DimDate[ContinuousBonusPeriod]), FILTER(ALL(DimDate), DimDate[DateKey] = TODAY()))
(Notice the ALL() statement)

SQLite - Determine average sales made for each day of week

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.

How to query for grouped results in Access, based on count of time and day of week?

I have a table in an Access 2013 database, which has many rows of incidents, each of which has a "time" column and a "day_of_week" column. I need to query for a result set that shows a count of incidents during hourly time ranges from 6:00am-5:00pm, per day of the week. I can get a total count of incidents per time range like so:
SELECT "6:00AM - 6:59AM" AS [Time Range],COUNT(time) AS [Count]
FROM Incidents
WHERE time >= #6:00:00 AM# AND time <=#6:59:00 AM#
UNION
SELECT "7:00AM - 7:59AM" AS [Time Range],COUNT(time) AS [Count]
FROM Incidents
WHERE time >= #7:00:00 AM# AND time <=#7:59:00 AM#
UNION
...
So on, and so forth. It is a lengthy query, but it gets the task done. However, as stated previously, I need to drill down further to figure out how many incidents occurred specifically during each hourly time frame, per day of the week. So, I need to have a column for "time", and then an additional column for each day of the week. I know this will involve some grouping, but I am not certain what must be done.
This is my first post here. Hopefully I followed the rules.
Thanks
This query should do what you need, except that it will only show hour as an hour number, rather than the expanded description your query fragment above shows:
select day_of_week, datepart("h",[time]) as hour_num, count(*)
from incidents
group by day_of_week, datepart("h",[time])
hope this helps