sql to find the weekdays in the month from the current day - sql

please help me with this. using SQL server 2008
I need to find the number of sales done on the current day.
then find the weekday from current date and based on that find the average of the sales on all those particular weekdays in the last month
ex:
select count(sales) from salestable where orderdate= getdate()
where it gives the count of the sales done on the current date
then I need to find out the average of the sales done on the same weekday for ex if today is Sunday find the average of the sales done in the last month on all Sundays in that month.

I recommend that you borrow the data warehousing technique of creating a Calendar table that you pre-populate with 1 row for every date within the range you might need. You can add to it basically any column that is useful - in this case DayOfWeek and MonthID. Then you can eliminate date math entirely and use joins - sort of like this (not complete but points you in the right direction):
select count(salestable.sales) as salescount, a.salesavg
from salestable
join calendar on salestable.orderdate = calendar.calendardate
join (
select monthid, dayofweek, avg(salestable.sales) as salesavg
from salestable
join calendar on salestable.orderdate = calendar.calendardate
group by monthid, dayofweek) as a
on calendar.monthid = a.monthid and calendar.dayofweek = a.dayofweek
where calendar.calendardate = getdate()
You create and populate the calendar table once and reuse it every time you need to do date operations. Once you get used to this technique, you will NEVER go back to date math.

For this kind of queries are Common Table Expressions very usefull. Then you can use DATEPART function to get day of week.

This solution is also untested and intended to just point you in the right direction.
This solution uses a co-related sub-query to get the average sales.
select
order_date,
count(sales) total_sales,
(select avg(sales)
from sales_table
where order_date between dateadd(day,-30,#your_date) and #your_date
and datepart(WEEKDAY,order_date) = datepart(WEEKDAY,#your_date)
) avg_sales_mth
from sales_table
where order_date = #your_date

Related

Bigquery: How can I aggregate the data of several columns according to a specific time range?

I am new to big query and I am trying to aggregate transaction data, revenue data, and visitor data across a series of client accounts. I need the output to be grouped by clientname and by 8 month period, so each client account has 12 months of data that are aggregated (each day of the month added together in one month entry). I can only manage to get an out of the first day of each month and not everything in between added together:
SELECT
clientname,
DATE_TRUNC(PARSE_DATE('%Y%m%d',date), MONTH) as MonthStart,
SUM (totals.visits) AS visits,
SUM (totals.transactions) AS transactions,
SUM (totals.campaigns) AS campaigns,
sum (totals.totalTransactionRevenue) AS Transactionsrevenue,
FROM `prod.mar.auto` as automotive
GROUP BY
clientname,monthstart
ORDER BY
clientname,monthstart ASC
Limit 1000
The out is only providing the value for the first of the month and not the sum between the months. Can someone help point me in the right direction?
Thanks
If you want data for the last 8 or 12 months, then use a WHERE clause:
SELECT a.clientname,
SUM(a.visits) AS visits,
SUM(a.transactions) AS transactions,
SUM(a.campaigns) AS campaigns,
SUM(a.totalTransactionRevenue) AS Transactionsrevenue,
FROM `prod.mar.auto` as a
WHERE PARSE_DATE('%Y%m%d',date >= DATE_ADD(CURRENT_DATE interval -12 months)
GROUP BY clientname
ORDER BY clientname ASC
Limit 1000;
Part of the question is somewhat unclear, so I'm doing my best with the information I have.
From my understanding of your question, it seems like there is an issue with aggregating across the entire month. It is only returning one day of the month, rather than summing across the month.
If you change
DATE_TRUNC(PARSE_DATE('%Y%m%d',date), MONTH) as MonthStart
to
EXTRACT(MONTH FROM DATE) AS MonthStart
This will return the number of the month and therefore you can aggregate across because the numbers across all the date fields will be the same for each month individually.
Here is the final query:
SELECT
clientname,
EXTRACT(MONTH FROM DATE) AS MonthStart,
SUM (totals.visits) AS visits,
SUM (totals.transactions) AS transactions,
SUM (totals.campaigns) AS campaigns,
sum (totals.totalTransactionRevenue) AS Transactionsrevenue,
FROM `prod.mar.auto` as automotive
GROUP BY
clientname, MonthStart
ORDER BY
clientname, MonthStart ASC
Limit 1000
Providing Documentation to Function:
https://cloud.google.com/bigquery/docs/reference/standard-sql/date_functions

Previous business day/ year over year from null

I am trying to pull year over year data by date from a database, but when the previous year falls on a holiday, the row is null. For example, 5/25/15 is the same day previous year for 5/23/16 this year. However, since 5/25/15 was Memorial Day, it didn't even create a row. So, I need the solution to pull the data from the last available business day.
Any help out there?
Obviously you are doing something like this:
from thisyear
join prevyear on thisyear.mmdd = prevyear.mmdd
i.e. joining on the precisely same month and day, when you should be doing something like:
from thisyear
cross apply
(
select top(1) * prevyear
where thisyear.mmdd >= prevyear.mmdd
order by prevyear.mmdd desc
) prevyear
i.e. find the closest month and day that was before or even on the same day.

How to get last and first date of every week from predefined date table (oracle SQL)

I have Table D_date in which all dates of a year, week number,quarter number etc attributes are defined. I just want to get first and last date of every week of year 2015.
Sample D_date tabe attached.
It is simple min/max if I understand you right
SELECT calendar_year_nbr, week, min(actual_date),max(actual_date)
FROM D_date
GROUP BY calendar_year_nbr, week
I just want to get first and last date of every week of year 2015.
Since you have precomputed values already stored in the table, you could directly use MIN and MAX as aggregate functions along with GROUP BY.
For example,
SELECT MIN(actual_date) min_date,
MAX(actual_date) max_date,
calendar_week_nbr
FROM d_date
WHERE calendar_year_nbr = 2015
GROUP BY calendar_week_nbr
ORDER BY min_date;
Another way is to use ROWNUM() OVER() analytic function.

How can I cross join the following query results with a table of dates

I am looking for a query which gives me the daily playing time. The start (first_date) and end date(last_update) are given as shown in the Table. The following query gives me the sum of playing time on given date. How can I extend it to get a table from first day to last day and plot the query data in it and show 0 on dates when no game is played.
SELECT startTime, SUM(duration) as sum
FROM myTable
WHERE startTime = endTime
GROUP BY startTime
To show date when no one play you will need create a table days with a date field day so you could do a left join. (100 years is only 36500 rows).
Using select Generate days from date range
This use store procedure in MSQL
I will assume if a play pass the midnight a new record begin. So I could simplify my code and remove the time from datetime field
SELECT d.day, SUM(duration) as sum
FROM
days d
left join myTable m
on CONVERT(date, m.starttime) = d.day
GROUP BY d.day
If I understand correctly, you could try:
SELECT SUM(duration) AS duration, date
FROM myTable
WHERE date <= 20140430
AND date => 20140401
GROUP BY date
This would get the total time played for each date between april 1 and april 30
As far as showing 0 for dates not in the table, I don't know.
Also, the table you posted doesn't show a duration column, but the query you posted does, so I went ahead and used it.

Calculating sales for a particular weekday in a given period in teradata

I have a table with transaction, date and their respective sales value. I need to calculate sum of Sales of all the distinct transactions on all Saturdays between date x and y. Teradata doesn't have a datename, datepart function. How can I do this?
I'm not Teradata expert, I don't even know it but I've found something. It's not a solution it's only suggestion of course, because you tell nothing about your db schema.
Source Dates and Times in Teradata (thru V2R4.1):
Computing the day of the week for a given date is not easy in SQL. If you need a weekday, I recommend that you look it up in the view sys_calendar.calendar (or join to it), thus:
select day_of_week
from sys_calendar.calendar
where calendar_date = date '2003-05-01';
day_of_week
-----------
5 [i.e. Thursday]
Did an inner join as
inner join sys_calendar.calendar as cal on cal.calendar_date=my_table.date where cal.day_of_week=7