Getting the average number of orders per day using mysql - 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.

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

datediff() query for multiple dates

I have a table named orders that contains order_id, order_date and order_shipped. I need to be able to query the difference in days between ordered and shipped for the whole table but only display the order_id's that have 15 or more days between them and I have no idea how to build that query.
Basically you want to select the ids where the date difference is at least 15.
SELECT order_id
FROM orders
WHERE datediff(order_shipped, order_date) >= 15
This could be slow if there are many orders, because the function result cannot be indexed and needs to be calculated every time.

DATEDIFF Current/Date for Last Record

I have a table "Report" with relevant columns "Date", "Doctor". Each doctor appears several times throughout the table. The following code is what I have at current:
SET #variable = (SELECT Date FROM Report WHERE Doctor='DocName' ORDER BY Date DESC LIMIT 1)
SELECT DATEDIFF(CURDATE(),#variable) AS DiffDate
This gives me the DATEDIFF for one doctor, without name. Is there any way to loop through the table, find the last row/date for each doctor, then perform a DATEDIFF on each individual doctor outputting a list of doctors with their DATEDIFFs (against current date) next to them?
Thanks in advance!
you can use group by to get only 1 row per doctor and max to select latest date:
select `Doctor`, DATEDIFF(CURDATE(),max(`Date`))
from `Report`
group by `Doctor`

How to get the average price for the X most recent rows based on date?

I am looking to calculate moving averages over variable dates.
My database is structured:
id int
date date
price decimal
For example, I'd like to find out if the average price going back 19 days ever gets greater than the average price going back 40 days within the past 5 days. Each of those time periods is variable.
What I am getting stuck on is selecting a specific number of rows for subquery.
Select * from table
order by date
LIMIT 0 , 19
Knowing that there will only be 1 input per day, can I use the above as a subquery? After that the problem seems trivial....
if you only have one input per day you don't need id, date can be your primary id? Am i missing something? Then use select sum
SELECT SUM(price) AS totalPrice FROM table Order by date desc Limit (most recent date),(furthest back date)
totalPrice/(total days)
I may not understand your question
Yes you can use that as a sub-query like this:
SELECT
AVG(price)
FROM
(SELECT * FROM t ORDER BY date DESC LIMIT 10) AS t1;
This calculates the average price for the latest 10 rows.
see fiddle.

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)