MySQL average two level agregation - mysql

Suppose I have a table with four fields in MySQL (id, week, day, value). The id field is an identifier for a device that takes several values per day.
What I want is calculate an average of value in a week-daily basis. The result will be other table with three fields (id, week, average_week_day_value), where the average value is not the average in a week basis, but in a week-daily basis. I mean: first we calculate the day-average, and after that, the week-day-average as an average of days-average-values per week.
Now, I implement that in two steps, with an intermediate table (id, week, day, average-day-value). After I have the intermediate table it's easy to calculate final table: (id, week, average_week_day_value)
Can I do that in a single step?
EDIT
First step query:
INSERT INTO daily (id,week,day,average)
SELECT id, week, day, avg(value)
FROM table_values
GROUP BY day
Second step query:
INSERT INTO weekly (id,week,avg)
SELECT id,week,avg(average)
FROM daily
GROUP BY week

You can just put your first query in a subquery.
SELECT week, AVG(day_avg)
FROM (
SELECT week, day, AVG(value) AS day_avg
FROM table_values
GROUP BY week, day
) d
GROUP BY week

Related

SQL query : aggregating records having a timestamped field, where fields timestamp falls in same time unit (sec, min, hour..)

I have a database table customers that records among others the arrival time of clients for a one month data. So, the customers table contains among other a column named arrival_time . (e.g., arrival_time = 12/1/2020 12:01:39 AM, arrival_time = 12/1/2020 12:01:34 AM etc…)
Is it possible to design/write an SQL query that returns the numbers of customers that arrived each second (or say, min, hour...) in this this one month data.
Thank you.
If you are using PostgreSQL you can use DATE_TRUNC(). For example:
select
date_trunc('minute', arrival_time) as at,
count(distinct customer_id) as cnt
from t
group by date_trunc('minute', arrival_time)
You can change 'minute' for 'day', 'week', 'second', etc. See https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC

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

Getting the average number of orders per day using mysql

I have the following table structure:
ID, User_ID, DateTime
Which stores a user id and datetime of an order purchased. How would I get the average number of orders a day, across every row?
In pseudo code I'm thinking:
Get total number of orders
Get number of days in range (from first row to last row).
Divide 1. by 2. to get average?
So it would return me a value of 50, or 100?
Thanks
Since you know the date range, and you are not guaranteed to have and order on these dates, you can't just subtract the max(date) from min(date), but you know the number of days before you run the query, therefore simply:
select count(*) / <days>
from mytable
where DateTime between <start> and <end>
Where you supply the indicated values because you know them.
select DATEDIFF(NOW(), date_time) as days, AVG(count(*))
from table
group by days
I have not tested the query, its just the idea, I guess it should work.

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)