There are referer records in my database. All records include date,clicks, scrolls, countries etc.
And in here, I successfully group referer records and include average values of clicks, scrolls, countries etc. However, I also want to enable date range, like last 3 days.
SELECT *, COUNT(*), COUNT(conv), AVG(clicks), AVG(scrolls),
AVG(spent) FROM track where referid='".$memberr."' GROUP BY
referer ORDER BY ".$sortby." desc limit 0,35
How can I integrate this last 3 days query with my mysql_query above ?
FROM_UNIXTIME(date,'%Y-%m-%d') > CURDATE() - INTERVAL 3 DAY
Pretty simple thing to do, you just need to add another condition:
WHERE date >= DATE_SUB(CURDATE(), INTERVAL 3 DAY) AND date <= CURDATE()
Related
I am trying to get monthly sales totals from a MYSQL database and have them summed by month with month name for last X months. The two columns I am targeting are: total_customer_charged and local_time. I almost have my query working correctly, the problem I have is that the order the results come out sometimes changes with each query. Can anyone please give me some hints to get my query correct?
My existing query is:
select date_format(local_time,'%M'),sum(total_customer_charged) FROM ORDERS WHERE local_time BETWEEN curdate() - INTERVAL 3 MONTH AND curdate() group by month(local_time) order by year(local_time),month(local_time)
You should put year into the group-by statement like this:
select
date_format(local_time, '%Y') AS agg_year,
date_format(local_time, '%m') AS agg_month,
sum(total_customer_charged) AS monthly_total_customer_charged
FROM
ORDERS
WHERE
local_time BETWEEN curdate() - INTERVAL 3 MONTH AND curdate()
group by
date_format(local_time, '%Y'),
date_format(local_time, '%m')
order by
agg_year,
agg_month
SELECT MONTHNAME(local_time), SUM(total_customer_charged)
FROM ORDERS
GROUP BY YEAR(local_time), MONTH(local_time)
My following query shows the date and the count of the emails found on each day (last 2 days)
My problem is that if no emails are found today, the today date will not be displayed on the output. (if yesterday has emails, it will show only 1 row with yesterday date and email).
How can I edit my query to always show 2 rows, today and yesterday, date and number of emails even zero?
SELECT maildate,
COUNT(*) AS totalEmails
FROM emails
WHERE maildate >= Date_add(Curdate(), interval - 2 DAY)
AND company_id = 1
GROUP BY DATE(maildate)
ORDER BY maildate desc
There are many tricks to creating a list of dates (or numeric sequences similarly). The one I like to use with MySQL is using #sqlvariables. I will typically start with a baseline value such as your date -2 days. I will do a cross-join to any other table in the database that has at least as many records as you expect in your output... Say 30 days, or a whole year 366 days, or longer. The inner sql variable prep will keep increasing itself by whatever increment (you could even do date ranges such as begin/end of a week, month, etc). Now you have your table of all possible dates you are looking to fill.
Now, I do a secondary query by the value -- in this case your email date and apply the group by. Using the where clause in this query will make IT faster since it can utilize the date on its query result set before returning for the LEFT-JOIN to the date range result set.
Now, your simple left-join gets both parts of all dates to be included and those corresponding counts that do exist.
Note the table alias "AnyTableWithAtLeast3RecordInIt" in the "JustDates" query could in-fact be your "emails" table. Since we don't care about any criteria except a record exists, and we are applying a limit of 30 days in my example, it will be instantaneous.
select
JustDates.DateToInclude,
coalesce( SumCnts.TotalEmails, 0 ) TotalEmails
from
( select
#myDate := DATE_ADD( #myDate, INTERVAL 1 DAY ) as DateToInclude
from
( select #myDate := Date_add(Curdate(), interval - 2 DAY) ) as SQLVars,
AnyTableWithAtLeast3RecordInIt
limit 30 ) JustDates
left join
( select
maildate,
COUNT(*) AS totalEmails
FROM
emails
WHERE
maildate >= Date_add(Curdate(), interval - 2 DAY)
AND company_id = 1
GROUP BY
DATE(maildate) ) SumCnts
ON JustDates.DateToInclude = SumCnts.MailDate
Now, judging by your query, but unclarified request... Your emails table CAN HAVE FUTURE DATES? Is that correct? Such as a Dr. Office and appointments are for the future and you want to get emails out for a given range. This is what I was inferring and hence had my limit to only go out 30 days... If you need longer, just extend the LIMIT clause.
You need a table that contains all dates in the needed range. If its only about today and yesterday, you can easily create it as a subquery (derived table).
SELECT Curdate() as maildate
UNION ALL
SELECT Curdate() - INTERVAL 1 DAY
http://rextester.com/ALH50651
Now you can LEFT JOIN your table and count the rows:
SELECT sub.maildate,
COUNT(m.maildate) AS totalEmails
FROM (
SELECT Curdate() as maildate
UNION ALL
SELECT Curdate() - INTERVAL 1 DAY
) sub
LEFT JOIN emails m
ON DATE(m.maildate) = sub.maildate
AND m.company_id = 1
GROUP BY sub.maildate
ORDER BY sub.maildate desc
I am trying to fetch rows only from specific date (like today, yesterday or 2 days ago) in mySQL. I have a column named "date" in my rows. (which includes dates like 1365053426).
$result=mysql_query("SELECT count(*) as total from track WHERE `date` >= CURRENT_DATE
AND `date` < CURRENT_DATE + INTERVAL 1 DAY");
I have tried this query, but it returns "0". What is the correct way to do that ?
how about using BETWEEN?
SELECT COUNT(*) as TotalCount
FROM Track
WHERE Date BETWEEN CURDATE() + INTERVAL -2 DAY AND CURDATE()
How about using datediff() function?
SELECT count(*) as total from track WHERE datediff(now(),date)=interval day
note: interval day could be declare from 0 -> up depends on what previous date you want to show
I need to select past 30 days data and find the no: rows....i am getting a warning if i am calculating the no: rows. So is there any other alternative to find no: rows in the selected section.....my code is:
$thirty_reg=mysql_query("SELECT * FROM user ORDER BY user.date DESC LIMIT 30");
$num_thirty=mysql_num_rows($thirty_reg);
echo $num_thirty;
A better suggestion to select the past 30 days data also is needed...
Modify your query to this to return rows for the past 30 days.
SELECT column FROM user WHERE user.date BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY) AND NOW()
However, I would recommend fetching the count of rows rather than a record set like so:
SELECT COUNT(*) FROM user WHERE user.date BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY) AND NOW()
SELECT count(id) FROM user WHERE user.date >= DATE_SUB(NOW(), INTERVAL 30);
Well someone beat me to it haha.
I am trying to write a query to select all records from users table where User_DateCreated (datetime field) is >= 3 months from today.
Any ideas?
SELECT *
FROM users
WHERE user_datecreated >= NOW() - INTERVAL 3 MONTH
If you want to ignore the time of day when a user was created you can use the following. So this will show someone created at 8:00am if you run Quassnoi's example query at 2:00pm.
SELECT *
FROM users
WHERE DATE(user_datecreated) >= DATE(NOW() - INTERVAL 3 MONTH)
Using DATE(user_datecreated) prevents mysql from using any indexes on the column, making the query really slow when the table grows.
You don't have to ignore the time when the user was created if you remove the time from the "3 months ago" date, as all the users created that day will match the condition.
SELECT *
FROM users
WHERE user_datecreated >= DATE(NOW() - INTERVAL 3 MONTH);