SQLite - Determine average sales made for each day of week - sql

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.

Related

SQL Rolling Count in Time Series

I have a SQLite table of companies and how many news articles was written about each company each day for 10 years (and about 3000 companies). I want to do a "rolling" count where for each company, I count the number of total news articles in a 3-day window, conditional on there being a positive number of news articles. For example, starting on day 1, if the number of articles is 0, skip and go to day 2, etc until we hit a day (say day 4) where there is 1 article, and then count the total number of articles in the next 3 days (so days 4,5,6). After that, I go to day 7 and keep scanning until I find the first day that has a news article, and repeat this 3-day sum, and keep scanning after that, etc. I will repeat this for each company.
I've thought of doing a rolling sum using window functions but with 3000 companies times 365*10 days of data rolling sum may computationally take too long, and plus I wouldn't need the sums to be computed on days that I skip over (so either days with 0 or days that are not the first days in the 3-day interval).
For example, the time series for each company may be (Day #:Number of Articles)
Day 1:0
Day 2:0
Day 3:0
Day 4:1
Day 5:3
Day 6:2
Day 7:0
Day 8:0
Day 9:20
Day 10:2
Day 11:0
Then the output would be
Day 4:6 (1 from Day 4, 3 from Day 5, and 2 from Day 6)
Day 9:22 (20 from day 9, 2 from day 10, 0 from day 11).
In the more recent versions of SQLite, you would use row_number():
select company, min(date), max(date), sum(num_articles)
from (select t.*,
row_number() over (partition by company order by date) as seqnum
from t
where num_articles > 0
) t
group by company, floor((seqnum - 1) / 3);

Power BI - Difference between amount per day and total in a table

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

Ms ACCESS: calculating past annual averages over varying date ranges

In a form on Ms ACCESS, a user can select a commodity (such as copper, nickel, etc.) from a list and a commodity price date from a list. A trailing 12 month average commodity price should then be calculated.
For example: the user selects Copper as commodity and February 1st 2010, 02/01/2010. I then want the average price to be calculated over the time period: [02/01/2009 - 02/01/2010].
I'm not sure how to write this in query form. This is the current incomplete code;
SELECT Avg(CommPrices.Price) AS Expr1,
FROM CommPrices
WHERE (((CommPrices.Commodity)=[Forms]![Tool Should Cost]![List243]))
AND CommPrices.DateComm = [Forms]![Tool Should Cost]![List55];
List243 is the list of commodities the user can select from, list55 is the list of dates the user can select. All data is obtained from the table CommPrices.
Note: the earliest dates in the column DateComm is 01/01/2008. So if the user selects a date for example 02/01/2008, then calculating the average over the past 12 months before 02/01/2008 won't be possible. I do want the code to still calculate the average using the dates available. (in the example it would just be the average over the past month)
Second Note: the column DateComm only has monthly dates for the first day of every month (e.g 01/01/2008, 02/01/2008, 03/01/2008). The dates listed in list55 can refer to different days in the month (e.g 03/16/2009), in that case I want the code to still calculate the past 12 month average using the closest commodity dates possible. So if the user selects date 03/16/2009, I want the code to calculate the 12 month average for 03/01/2008 - 03/01/2009.
For "integer" months it would be:
SELECT
Avg(CommPrices.Price) AS AveragePrice,
FROM
CommPrices
WHERE
CommPrices.Commodity=[Forms]![Tool Should Cost]![List243]
AND
CommPrices.DateComm = BETWEEN
DateSerial(Year([Forms]![Tool Should Cost]![List55]) - 1, Month([Forms]![Tool Should Cost]![List55]), 1)
AND
DateSerial(Year([Forms]![Tool Should Cost]![List55]), Month([Forms]![Tool Should Cost]![List55]), 1)

Oracle Week Number from a Date

I am brand new to Oracle. I have figured out most of what I need but one field is driving me absolutely crazy. Seems like it should be simple but I think my brain is fried and I just can't get my head around it. I am trying to produce a Sales report. I am doing all kinds of crazy things based on the Invoice Date. The last thing I need to do is to be able to create a Week Number so I can report on weekly sales year vs year. For purposes of this report my fiscal year starts exactly on December 1 (regardless of day of week it falls on) every year. For example, Dec 1-7 will be week 1, etc. I can get the week number using various functions but all of them are based on either calendar year or ISO weeks. How can I easily generate a field that will give me the number of the week since December 1? Thanks so much for your help.
Forget about the default week number formats as that won't work for this specific requirement. I'd probably subtract the previous 1 December from invoice date and divide that by 7. Round down, add 1 and you should be fine.
select floor(
(
trunc(invoiceDate) -
case
-- if December is current month, than use 1st of this month
when to_char(invoiceDate, 'MM') = '12' then trunc(invoiceDate, 'MM')
-- else, use 1st December of previous year
else add_months(trunc(invoiceDate, 'YYYY'), -1)
end
) / 7
) + 1
from dual;

Access query (SQL) to return records sorted (grouped by) WEEKS

Greetings SQL gurus,
I don't know if you can help me, but I will try. I have several large databases grouped by year (each year in a different database). I want to be able to compare values from a particular week from one year to the next. For example, "show me week 17 of 2008 vs. week 17 of 2002."
I have the following definition of weeks that ideally I would use:
Only 52 weeks each year and 7 days a week (that only takes 364 days),
The first day of the first week starts from January 2nd - which means we do not use January 1st data, and
In leap year, the first day of the first week ALSO starts from the January 2nd plus we skip Feb. 29.
Any ideas?
Thanks in advance.
Best to avoid creating a table because then you have to update and maintain it to get your queries to work.
DatePart('ww',[myDate]) will give you the week number. You may run into some issues though deciding which week belongs to which year - for example if Jan 1 2003 is on Wednesday does the week belong as week 52 in 2002 or week 1 in 2003? Your accounting department will have a day of the week that is your end of week (usually Sat). I usually just pick the year that has the most days in it. DatePart will always count the first week as 1 and in the case of the example above the last week as 53. You may not care that much either way. You can create queries for each year
SELECT DatePart('ww',[myDate]) as WeekNumber,myYearTable.* as WeekNumber
FROM myYearTable
and then join the queries to get your data. You'll loose a couple days at the end of the year if one table has 52 weeks and one has 53 (most will show as 53). Or you can do it by your weekending day - this always gives you Saturday which would push a late week into the following year.
(7-Weekday([myDate]))+[myDate]
then
DatePart('ww',(7-Weekday([myDate]))+[myDate])
Hope that helps
To get the week number
'to get the week number in the year
select datepart( week, datefield)
'to get the week number in the month
select (datepart(dd,datefield) -1 ) / 7 + 1
You don't need to complicate things thinking about leap years, etc. Just compare weeks mon to sun
SInce you havea a specifc defintion of when the week starts that is differnt that the standard used by the db, I think a weeks table is the solution to your problem. For each year create a table that defines the dates contained in each week and the week number. Then by joining to that table as well as the relevant other tables, you can ask for just the data for week 17.
Table structure
Date Week
20090102 1
20090103 1
etc.
I needed to create a query that shows BOTH year AND week numbers, like 2014-52. The year shows correct when you use the Datepart() formula to convert week 53 to week 52 in the previous year, but shows the wrong year for the week that was week 1 previously that should be week 52 now. It show that week as 2015-52 instead of 2014-52.
Furthermore, it sorts the data wrong if you only use only the week number, eg:
2014-1,2014-11,2014-2
To overcome this I created the following query to insert a 0 and also to check for days in week 1 that should still fall under week 52.
ActualWeek: IIf(DatePart("ww",[SomeDate],1,3)=52 And DatePart("ww",[SomeDate])=1, DatePart("yyyy",[SomeDate],1,3)-1,DatePart("yyyy",[SomeDate],1,3)) & "-" & IIf(DatePart("ww",[SomeDate],1,3)<10,"0" & DatePart("ww",[SomeDate],1,3),DatePart("ww",[SomeDate],1,3))