Calculate in SQL Average number of active subscriptions per quarter - sql

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;`

Related

How to compare and find the highest average number of a value occurance in SQL for specific months?

I am fairly new to SQL and need help to find which customer has the highest average number of event occurring by month in the years (2019 - 2020) and which is the top 3 busy month every year?
Please note one customer can have multiple event_IDs.
Table Snippet:
event_ID
cust_ID
event_datetime
abc123
cus11
2019-03-13T00:00:00
abc124
cus12
2020-05-23T02:34:35
abc125
cus457
2018-12-12T22:12:23
abc126
cus11
2017-01-07T13:54:56
abc127
cus7897
2021-07-11T04:43:23
I need to find the customers having the highest average number of events in the respective month( cust with highest number of events on avg in 2019, 2020, 2021).
month
cust_ID
avg_num
1
cus11
9345.8
2
cus4563
11898.5
I have tried using CTE and window functions but couldn't figure out the logic to get to the result, any help is appreciated!
EDIT:
For clarification, my example is just a snippet of the table, the actual table has more than a few million rows, I need the customer who has the maximum number of events occurring on average over month 1,2,3,.. and avg_num will have the average value of the number of event for the cust_ID with max number of event-[ (num of event in 2019 + 2020 + 2021)/3 ]
Maybe something like this:
SELECT cust_id
, COUNT(*) AS number_of_events
, EXTRACT(YEAR FROM MAX(event_datetime)) last_year_for_cust_id
, EXTRACT(YEAR FROM MIN(event_datetime)) first_year_for_cust_id
, CAST(COUNT(*) AS DECIMAL) / (EXTRACT(YEAR FROM MAX(event_datetime)) - EXTRACT(YEAR FROM MIN(event_datetime)) )
FROM table_name
GROUP BY cust_id
ORDER BY cust_id; -- or something else
I didn't test it, no idea what brand of database you use and no DB<>fiddle was available.

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

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

show no of hours each week for specific project id sql

I have table like this:
Now I want to see sum of hour for each week for each project .How can i query that.
I tried with query
select CurrentData.STATUS,
sum(CurrentData.HOURS), CurrentData.WEEKS
from CURRENT_DATA CurrentData
group by currentData.HOURS, CurrentData.STATUS, CurrentData.WEEKS, CurrentData.PROJECT_ID
having currentData.WEEKS = CurrentData.WEEKS
order by CurrentData.WEEKS;
But still each week coming as separate rows.Not sure how to do it
Do not use HOURS in group by. The are in the group function SUM:
SELECT PROJECT_ID, STATUS, YEARS, WEEKS, SUM (CurrentData.HOURS)
FROM CURRENT_DATA
GROUP BY PROJECT_ID, STATUS, Years, WEEKS
ORDER BY Years, WEEKS
And what is in the having clause. That is always true. Do you want a certain week and year? And you can get rid of "CurrentData.". You have only one table and you don't need alias for this table.
Here filtered for year 2016 and summed for all project id :
SELECT STATUS, WEEKS, SUM (CurrentData.HOURS)
FROM CURRENT_DATA
WHERE Years = 2016
GROUP BY STATUS, WEEKS
ORDER BY WEEKS

How to create a dynamic where clause in sql?

So I have created a table that has the following columns from a transaction table with all customer purchase records:
1. Month-Year, 2.Customer ID, 3. Number of Transactions in that month.
I'm trying to create a table that has the output of
1. Month-Year, 2. Number of active customers defined by having at least 1 purchase in the previous year.
The code that I have currently is this but the case when obviously only capturing one date and the where clause isn't dynamic. Would really appreciate your help.
select month_start_date, cust_ID,
(case when month_start_Date between date and add_months(date, -12) then count(cust_ID) else 0 end) as active
from myserver.mytable
where
month_start_Date>add_months(month_start_date,-12)
group by 1,2
EDIT: I'm just trying to put a flag next to a customer if they are active in each month defined as having at least one transaction in the last year thanks!
You might use Teradata's proprietary EXPAND ON synax for creating time series:
SELECT month_start_date, COUNT(*)
FROM
( -- create one row for every month within the next year
-- after a customer's transaction
SELECT DISTINCT
BEGIN(pd) AS month_start_date,
cust_ID
FROM myserver.mytable
EXPAND ON PERIOD(month_start_date, ADD_MONTHS(month_start_date,12)) AS pd
BY ANCHOR MONTH_BEGIN -- every 1st of month
FOR PERIOD (DATE - 500, DATE) -- use this to restrict to a specific date range
) AS dt
GROUP BY month_start_date
ORDER BY month_start_date

PL SQL - newbie - MAX fron table and avg

I have a table of account numbers by date and 24 hourly intervals
ACCT# ; Date ; hour1, hour2, hour3......hour24
there could be as many as 365 days per account# I would like to find the average of all the intervals as well as the as max interval for each acct#. I tried to add sample data but since it is my first post I can't attach it (need+10 posts) –
"customer_number" "date" "est_hb_0000" "est_hb_0100" "est_hb_0200" "est_hb_0300" "est_hb_0400" "est_hb_0500" "est_hb_0600" "est_hb_0700" "est_hb_0800" "est_hb_0900" "est_hb_1000" "est_hb_1100" "est_hb_1200" "est_hb_1300" "est_hb_1400" "est_hb_1500" "est_hb_1600" "est_hb_1700" "est_hb_1800" "est_hb_1900" "est_hb_2000" "est_hb_2100" "est_hb_2200" "est_hb_2300"
Thanks in advance for your help
This SQL should get you close, after you have restructured and populated the table.
Select Customer, Date, HourOfDay, NumAccts
From ActivityStats
Where Customer = 'zzz'
and Date = 'Dt'
and RowNumber < 11
Order By NumAccts Desc