SQL to calculate daily average for a column with records of some dates are missing - sql

I have table like below:
I have to calculate daily average count of session for each user.
First i calculated, total no of sessions for each day for every user and from that i tried to calculate average of daily session. I understand that it wont work since all users dont have sessions for every date.Some dates are missing for all users. Is there any way to calculate daily average when there is no entries for some dates
WITH daily_count AS
(
SELECT user_id, to_char(local_time,’MM/DD/YYYY’) AS Date, count(session_id) AS total_count
FROM table_name
GROUP BY device_id, to_char(local_time,’MM/DD/YYYY’)
)
SELECT user_id , AVG(total_count) AS average_session_count
FROM daily_count
GROUP BY user_id
For eg: The max date in the above given table is Feb04 and the min date is Jan31 .So the total no of days is 5 days.If we take Userid 1, it is having records only for 2 dates. So the query i wrote will calculate average for 2 days not for 5 days. How to make it to calculate average for 5 days

if for date 1,2,3 number of sessions for one user is 1,0(no sessions),5 then what output do you want in average sessions? --> 2 or 3?
You need to change your main query as follows:
SELECT USER_ID,
AVG(TOTAL_COUNT) AS AVERAGE_SESSION_COUNT -- if you want output as 3 then use this
--SUM(TOTAL_COUNT)/(MAX(DATE) - MIN(DATE) + 1) -- if you want output as 2 then use this
FROM DAILY_COUNT
GROUP BY USER_ID

Related

Calculate in SQL Average number of active subscriptions per quarter

I need a help please
I have a table with such fields: subscription_id, client_id, start_date, end_date.
Subscription is active when started but haven’t ended.
How I can calculate average number of active subscriptions per quarter?
I have issues with getting the active period for each subscription (between start and end date) and then by grouping it by quarters and years
I was trying this sQL ,but it dosen't work
`WITH total AS (
SELECT
QUARTER(w.start_date) AS QUARTER_start, CONCAT("Y", YEAR(w.start_date)," ", "Q-", QUARTER(w.start_date)) AS "startYQ"
,QUARTER(w.end_date) AS QUARTER_end, CONCAT("Y", YEAR(w.end_date)," ", "Q-", QUARTER(w.end_date)) AS "endYQ"
,count(w.subscription_id) as subscription_id
FROM work w
GROUP BY 1,2,3,4
ORDER BY 2
)
SELECT t.endYQ, AVG(t.subscription_id) as avg_p
FROM total t
group by endYQ
order by 1;`

Find most recent date of purchase in user day table

I'm trying to put together a query that will fetch the date, purchase amount, and number of transactions of the last time each user made a purchase. I am pulling from a user day table that contains a row for each time a user does anything in the app, purchase or not. Basically all I am trying to get is the most recent date in which the number of transactions field was greater than zero. The below query returns all days of purchase made by a particular user when all I'm looking for is the last purchase so just the 1st row shown in the attached screenshot is what I am trying to get.
screen shot of query and result set
select tuid, max(event_day),
purchases_day_rev as last_dop_rev,
purchases_day_num as last_dop_quantity,
purchases_day_rev/nullif(purchases_day_num,0) as last_dop_spend_pp
from
(select tuid, event_day,purchases_day_rev,purchases_day_num
from
app.user_day
where purchases_day_num > 0
and tuid='122d665e-1d71-4319-bb0d-05c7f37a28b0'
group by 1,2,3,4) a
group by 1,3,4,5
I'm not going to comment on the logic of your query... if all you want is the first row of your result set, you can try:
<your query here> ORDER BY 2 DESC LIMIT 1 ;
Where ORDER BY 2 DESC orders the result set on max(event_day) and LIMIT 1 extracts only the first row.
I don't know all of the ins and outs of your data, but I don't understand why you are grouping within the subquery without any aggregate function (sum, average, min, max, etc). With that said, I would try something like this:
select tuid
,event_day
,purchases_day_rev as last_dop_rev
,purchases_day_num as last_dop_quantity
,purchases_day_rev/nullif(purchases_day_num,0) as last_day_spend_pp
from app.user_day a
inner join
(
select tuid
,max(event_day) as MAX_DAY
from app.user_day
where purchases_day_num > 0
and tuid='122d665e-1d71-4319-bb0d-05c7f37a28b0'
group by 1
) b
on a.tuid = b.tuid
and a.event_day = b.max_day;

ACCESS: Get total time different and amount of time ranges above a set amount

I have a table that I'm trying to not only get the sum of time(hours) difference between two columns but also the amount of times a time difference is above a set amount, 6 in this case.
The total I got from Getting the sum of a datediff result but can I in the same query also get count(*) where datediff => 6?
Thanks in advance for any and all help.
DateDiff used for hours will probably not be useful, as it will return 1 hour from, say 10:55 to 11:03.
So count minutes:
Select
*, DateDiff("n", [TimeStart], [TimeEnd]) / 60 As Hours
From
YourTable
Save this query and use it as source in a new query to count those entries with an hour count greater than or equal to six:
Select Count(*) As Entries
From YourQuery
Where Hours >= 6

Find the timestamp of a unique ticket number

I have a table that looks like this:
**ActivityNumber -- TimeStamp -- PreviousActivityNumber -- Team**
1234-4 -- 01/01/2017 14:12 -- 1234-3 -- Team A
There are 400,000 rows.
The ActivityNumber is a unique ticket number with the activity count attached. There are 4 teams.
Each activitynumber is in the table.
I need to calculate the average time taken between updates for each team, for each month (to see how each team is improving over time).
I produced a query which counts the number of activities per team per month - so I'm part way there.
I'm unable to find the timestamp for the previousActivityNumber so I can subtract it from the current Activity number. If I could get this, I could run an average on it.
Conceptually:
select a1.Team,
a1.ActivityNumber,
a1.TimeStamp,
a2.Timestamp as PrevTime,
datediff('n',a1.Timestamp, a2.timestamp) as WorkMinutes
from MyTable a1
left join MyTable a2
on ((a1.Team = a2.Team)
and (a1.PreviousActivityNumber = a2.ActivityNumber )

Display a rolling 12 weeks chart in SSRS report

I am calling the data query in ssrs like this:
SELECT * FROM [DATABASE].[dbo].[mytable]
So, the current week is the last week from the query (e.g. 3/31 - 4/4) and each number represents the week before until we have reached the 12 weeks prior to this week and display in a point chart.
How can I accomplish grouping all the visits for all locations by weeks and adding it to the chart?
I suggest updating your SQL query to Group by a descending Dense_Rank of DatePart(Week,ARRIVED_DATE). In this example, I have one column for Visits because I couldn't tell which columns you were using to get your Visit count:
-- load some test data
if object_id('tempdb..#MyTable') is not null
drop table #MyTable
create table #MyTable(ARRIVED_DATE datetime,Visits int)
while (select count(*) from #MyTable) < 1000
begin
insert into #MyTable values
(dateadd(day,round(rand()*100,0),'2014-01-01'),round(rand()*1000,0))
end
-- Sum Visits by WeekNumber relative to today's WeekNumber
select
dense_rank() over(order by datepart(week,ARRIVED_DATE) desc) [Week],
sum(Visits) Visits
from #MyTable
where datepart(week,ARRIVED_DATE) >= datepart(week,getdate()) - 11
group by datepart(week,ARRIVED_DATE)
order by datepart(week,ARRIVED_DATE)
Let me know if I can provide any more detail to help you out.
You are going to want to do the grouping of the visits within SQL. You should be able to add a calculated column to your table which is something like WorkWeek and it should be calculated on the days difference from a certain day such as Sunday. This column will then by your X value rather than the date field you were using.
Here is a good article that goes into first day of week: First Day of Week