Generating monthly report mysql - mysql

I have a table in which there are 5 columns,
id (auto incrementing number), titleId, version, created_at
A combination of titleId and version is always unique. I want to find out for each day for the past 1 month, how many unique titleIds were present along with the count of how many entries per day. This is because on a given day there might be multiple versions of the same titleId.
select count(*) from titles where created_at >= '2019-08-12 00:00:00' and created_at <= '2019-08-13 00:00:00' will give me total number of titles which came on 12th August
and
select count(distinct titleId) from titles where created_at >= '2019-08-12 00:00:00' and created_at <= '2019-08-13 00:00:00'
will give me the count of unique titles on the 12th August. Is there a way for me to generate the data for the past 30/60 days?
I know I can run this command manually 30 times by changing the date to get the numbers, but was wondering if there is a better way to do this in mysql

As long as there is an entry every day, this query should give you the data for each day for the last 30:
select date(created_at) as cdate, count(distinct titleId) as cnt
from titles
where created_at >= cur_date() - interval 30 day
group by cdate

Related

Collect last 7 days data from SQL and group by days

how can I count last 7 days data from SQL and group them by day/date (excluding today).
I should be able to use the result as $resultday1, $resultday2, $resultday3 etc.
If there was 10 total SQL entries in day 1 (yesterday) $resultday1 should show "10".
and the days should be last 7 only, and today/current day should not consider.
The following PHP SQL script shows the total count only
SELECT COUNT(1) FROM orders WHERE username='jondoe'
database is a list of referrals made by a registered user in previous days.
a single table contains all user's referral details, table name "orders" as per above example.
This is the exact query as you want
SELECT
COUNT(*), DATE(order_date) order_date
FROM
orders
WHERE
order_date < CURDATE()
AND order_date > DATE_SUB(NOW(), INTERVAL 7 DAY)
GROUP BY order_date
ORDER BY order_date DESC;

The matched days count between two dates ranges

I have two dates for reservation for example I have reservation starts at 2020-03-01
and ends at 2020-04-10.
So when I make select query to know how many days this room has been reserved in the 4th month i want to get count of days 10
Is there anyway to do it in Mysql.
SELECT from_date , to_date
FROM reservations
WHERE room_id = ?
AND from_date >= "2020-04-01" AND to_date >= "2020-04-30"
You can use datediff() andleast()andgreatest()`. I think the logic you want is:
SELECT DATEDIFF(LEAST(to_date, '2020-04-30'),
GREATEST(from_date, '2020-04-01')
) + 1
FROM reservations
WHERE room_id = ? AND
to_date >= '2020-04-01' AND
from_date <= '2020-04-30';
Note that the date logic in the WHERE clause has been modified. This is the correct logic for determining if two time periods overlap. The first ends after the second starts; the first starts before the second ends.

Select between dates with count condition

I have table user with column login_time.
I want to select all the users that have logged in more than 10 times in a month.
I tried something like this:
SELECT login_time, count(id) as loginCount FROM user
WHERE login_time between DATE_SUB(login_time INTERVAL 1 month) AND login_time
GROUP BY id, MONTH(login_time) HAVING loginCount > 10;
Im not sure about my selection between dates.
How can I select with a month intervals avoiding double records.
For example if I have this values for login_time:
1. '2015-02-01 14:05:19'
2. '2015-01-21 14:05:19'
3. '2015-01-11 14:05:19'
Both 3 and 2 are within month range of 1.
So will I get double records for that values?
To find the users who have logged in more than ten times in the month ending right now, do this.
SELECT COUNT(*) times_logged_in,
userid
FROM user
WHERE login_time >= NOW() - INTERVAL 1 MONTH
GROUP BY user_id
HAVING COUNT(*)> 10
To find the users who have logged in more than ten times in any calendar month in your table, do this.
SELECT COUNT(*) times_logged_in,
DATE(DATE_FORMAT(login_time, '%Y-%m-01')) month_beginning,
userid
FROM user
GROUP BY user_id, DATE(DATE_FORMAT(login_time, '%Y-%m-01'))
HAVING COUNT(*)> 10
The trick here is the expression DATE(DATE_FORMAT(login_time, '%Y-%m-01')), which converts any timestamp to the first day of the month in which it occurs.
Your question mentioned this WHERE condition:
WHERE login_time between DATE_SUB(login_time INTERVAL 1 month) AND login_time
This doesn't do anything interesting because it always comes back true. Each given login_time always falls in the interval you specified.
Edit: You can GROUP BY MONTH(dt) if you want. But the way I have shown it automatically accounts for years as well as months, so in my opinion it's much better for accurate reporting.
Another edit: This formula yields the preceding Sunday for any given date or timestamp item.
FROM_DAYS(TO_DAYS(login_time) -MOD(TO_DAYS(login_time) -1, 7))
If Monday is the first day of the week in your jurisdiction, change the -1 to -2. Grouping by this function is superior to doing GROUP BY WEEK(login_time) because WEEK() does odd things at the beginnings and ends of calendar years.
This is all written up in more detail here: http://www.plumislandmedia.net/mysql/sql-reporting-time-intervals/

Mysql - Find increased value over a week

Score Table
user_idx (int)
date (datetime)
score (int)
I need to find out how much total score has increased over a week from today's date. I know that I need two of the same user tables grouped by user_idx that one contains total scores from the past to today and the other contains total scores from the past to a date of a week ago.
After that, by substracting one from the other will give me the answer... but I'm struggling to write effective sql query that does it.
I've tried
SELECT BLAH BLAH
FROM (SELECT user_idx, COUNT(*) as last_week_study_amount
FROM user_table
WHERE date <= date_sub(now(),INTERVAL 1 WEEK)
GROUP BY user_idx)
AS a WHERE .....
Could you help me :( ?
Let me clear you want to get total count in last week.
Try below query
SELECT *
FROM (SELECT user_idx, COUNT(*) as last_week_study_amount
FROM user_table
WHERE date <= date_sub(now(),INTERVAL 1 WEEK)
GROUP BY user_idx)
AS a WHERE .....
SELECT (SUM(score) - last_week_score) AS increased_score,
FROM user a
JOIN (SELECT b.user_idx, COUNT(*) as last_week_score
FROM userb
WHERE date<= date_sub(now(),INTERVAL 1 WEEK)
GROUP BY b.user_idx) As c ON a.user_idx = c.user_idx
WHERE DATE(date) <= DATE(NOW())
GROUP BY a.user_idx
I ended up writing this code and I think this one is working okay... not sure if it's the best or has a critical error. I will update it if it turns out to be a bad one...

Count unique users from statistics table based on hourly groupby

We have a statistical database for our Facebook application. One of our outputs is Unique Facebook Users based on time range. If our customers select daily usage, we show them a graph of unique Facebook users per hour.
My problem is with the unique values. First, here is the relevant columns from the table:
timestamp---facebookID---actionID---producerID
My current query is:
SELECT HOUR(timestamp) as Hour, COUNT(DISTINCT facebookID) as Events
FROM `e4s_analytic_data`
WHERE actionID = 'ax' AND producerID = '2' AND timestamp BETWEEN'12-06-11 0:00:00' and '12-06-11 23:59:59'
GROUP BY HOUR(timestamp)
This gives unique visitors (Based on facebookID) per hour. But if id = 123 visited in 14 and then visited again in 17, He will be counted twice - firstly in 14 and then in 17.
To solve this I've tried to add an inner query that will give all the ids that are already in the table from earlier hours.
I thought to bring all facebookIDs already listed in the table from 0 (The start of the day) until the current hour (taken from each row from the outside SELECT) and remove them from the outside SELECT. So that every COUNT will only include new Facebook IDs. Here is what I've tried:
SELECT HOUR(timestamp) as Hour, COUNT(DISTINCT facebookID) as Events
FROM `e4s_analytic_data`
WHERE actionID = 'ax' AND producerID = '2' AND timestamp between '12-06-11 0:00:00' and '12-06-11 23:59:59'
AND facebookID NOT IN
( SELECT facebookID FROM `e4s_analytic_data`
WHERE actionID = 'ax' AND producerID = '2' AND
HOUR(timestamp) >= 0 AND HOUR(timestamp) < Hour
)
GROUP BY HOUR(timestamp)
But it gives me this error:
Unknown column 'Hour' in 'where clause'
How can I solve this ?
Thanks.
EDIT: Sample data:
timestamp--------------facebookID--------producerID-------actionID
2012-06-13 12:38:55 ******6513406 2 ax
2012-06-13 08:49:55 ******6513406 2 ax
The query returns 1 unique visitor at 8 and 1 unique visitor at 12. I want to return only 1 unique at 8, because at 12 it is the same visitor from 8.