SQL average number of requests per user over time period - mysql

I have a table (Requests) with the following fields:
id, requestType, userEmail, date
I want to find the average number of requests per user over a given period (i.e. over the last month). Any suggestions?
Thanks!
Greg

Something like SUM feature will work. Might be a little slow.
SELECT SUM(requestType) FROM Requests WHERE `userEmail` = `userEmail` and `date` BETWEEN `first-date YYYY-MM-DD` AND `second-date YYYY-MM-DD`;
SQL SUM
I would also recommend, if you have a lot of request, to have one row per user per day and just update the request total for that user.
Edit: If you want the last 30 days something like this query should work. It worked on my test table.
SELECT SUM(requestType) FROM Requests WHERE `userEmail` = `userEmail` and `date`BETWEEN curdate() - INTERVAL 30 DAY AND curdate();

Related

Calculate average session length per daily active user?

I'm pretty new to SQL and I'm struggling with one of the questions on my exercise. How would I calculate average session length per daily active user? The table shown is just a sample of what the extended table is. Imagine loads more rows.
I simply used this query to calculate the daily active users:
SELECT COUNT (DISTINCT user_id)
FROM table1
and welcome to StackOverflow!
now, your question:
How would I calculate average session length per daily active user?
you already have the session time, and using AVG function you will get a simple average for all
select AVG(session_length_seconds) avg from table_1
but you want per day... so you need to think as group by day, so how do you get the day? you have a activity_date as a Date entry, it's easy to extract day, month and year from it, for example
select
DAY(activity_date) day,
MONTH((activity_date) month,
YEAR(activity_date) year
from
table_1
will break down the date field in columns you can use...
now, back to your question, it states daily active user, but all you have is sessions, a user could have multiple sessions, so I have no idea, from the context you have shared, how you go about that, and make the avg for each session, makes no sense as data to retrieve, I'll just assume, and serves this answer just to get you started, that you want the avg per day only
knowing how to get the average, let's create a query that has it all together:
select
DAY(activity_date) day,
MONTH((activity_date) month,
YEAR(activity_date) year,
AVG(session_length_seconds) avg
from
table_1
group by
DAY(activity_date),
MONTH((activity_date),
YEAR(activity_date)
will output the average of session_length_seconds per day/month/year
the group by part, you need to have as many fields you have in the select but that do not do any calculation, like sum, count, etc... in our case avg does calculation, so we don't want to group by that value, but we do want to group by the other 3 values, so we have a 3 columns with day, month and year. You can also use concat to join day, month and year into just one string if you prefer...

Sql to get number of hours per user per day

A table 'Log' has the below columns:
SystemName
User
Datetime - it's a timestamp
Status - has the values Start or Stop.
I need to write a query which will give me :
Number of hours spent per user per day on system X.
Please see example data below:
X, Amit, 05/01/2019 08:45:00, Start
X, Amit, 05/03/2019 13:25:00, Stop
X, Dave, 05/01/2019 09:10:35, Start
X, Dave, 05/01/2019 17:35:42, Stop
Output:
Amit,05/01/2019, 15h
Amit,05/02/2019, 24h
Amit,05/03/2019, 9h
Dave,05/01/2019, 8h
My approach till now :
I was thinking I could use lead or lag to get the consecutive times in the same row. But in the case of user Amit that spans across multiple days. Also there could be a user who has started and stopped multiple times on the same day. Even if I do that how could I generate hours for the dates amidst the range. Can you please help me.
This should work. You will only get Hours spent if both Start and Stop status exists for a user in a single day.
SELECT SystemName,[user],
CONVERT(varchar, CAST(Datetime AS DATETIME), 1) Datetime,
DATEDIFF
(
HH,
MAX(CASE WHEN Ststus = 'Start' THEN [Datetime] ELSE NULL END ),
MAX(CASE WHEN Ststus = 'Stop' THEN Datetime ELSE NULL END )
)HourSpent
FROM your_table A
GROUP BY SystemName,[User],
CONVERT(varchar, CAST(Datetime AS DATETIME), 1)
Since the output consists of one row per User + Day, then you would need to JOIN the data to a calendar table of dates.
You would need a way to extract the Start and Stop timestamp pairs for a given user, join it to the calendar table, then count the number of hours on that day that are between the start and stop times. (The hour count could be use a User Defined Function.
That's pretty complex. Frankly, I would rather write a Python program to parse the data rather than doing it via SQL. It would be very simple:
Read start line
Read end line
Loop through days, outputting hours per day (quite simple in Python)
Sometimes the best hammer is a spanner. (Translation: Sometimes a different tool is better.)

MySQL: Select count of returning vs. new rows in MySQL with period

I have database table in MySQL, which consist of the following fields:
id
user_id
timestamp
The table is a simple log of visitors. I am trying to get the following numbers in one query:
Distinct user_id's for a specific time period (30 days)
Amount of these user_id's, which already exist in the table, regardless of time period
I have been able to do it within the period with this simple query:
SELECT
COUNT(DISTINCT user_id) AS 'count_distinct',
COUNT(user_id) AS 'count_all'
FROM
table
WHERE
timestamp BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE();
Running this query gives me the count of distinct user_id's and the count of all user_id's within the time period. I can then apply the math myself to get the count of new vs. returning visitors - for that period. What I am trying to figure out is how many distinct user_id's, who visited within 30 days, who has also visited at any previous point in time.
I hope you can help me solve this.

SQL Statement to get daily totals

I'm storing some data in a table and I want to be able to display the total data points per day on the graph. So the first graph point might be 7 for Monday, Jan 1, 2013, and then 3 for Tuesday, Jan 2, 2013...etc.
I have full time/date stamps for each of my data points in my table of SQL type datetime.
My pseudo statement looks like this, but I'm concerned since I'm using the datetime data type:
SELECT
DATE(created_at) AS create_date
COUNT(id) AS total
FROM
data_table
GROUP BY
create_date
How can I get the total data points per day, regardless of the timestamp?
Try this
SELECT
DATE(created_at) AS create_date,
COUNT(id) AS total
FROM
data_table
GROUP BY
DATE(created_at)
Best would be to start a daily cron job that stores the number of the data points for every day. So you can every day count the number between let's say 24.00.00 to 23.59.59.
If you want to count them on the fly you might have slow requests on huge data amounts, since the grouping query cannot use table index.
But maybe you can add a new table column where you store just the date additionally to the timestamp.

Need mysql query to add values for each day in a time series... Need help

I have a transaction table and I'm looking to generate a dataset to drive a line chart that shows the sum of all the sales happened on each day during a given period. I have never grouped results like that before and am scratching my head.
Let's say the table is called "transactions", the "datetime" field is called timestamp, and the sales amount on each transaction is "txn_amount". I want the result set to include each day: "1/2/10" and the sum of the transaction amounts.
I need to get a book and spend a week learning mysql... Thanks for helping me out.
select sum(txn_amount) ,timestamp from transactions where timestamp in (select distinct timestamp from transactions) group by timestamp
if datatype is datetime,Use this
select sum(amt) ,substring(dt,1,10) from transactions where substring(dt,1,10) in (select distinct substring(dt,1,10) from transactions) group by substring(dt,1,10)