Counting all rows in column with two different date conditions - mysql

I'm trying to turn two count queries with date conditions (the ones below) into one query.
SELECT COUNT(*) as yesterday FROM orders WHERE DATE(timedate) = DATE(NOW() - INTERVAL 1 DAY)
SELECT COUNT(*) as yesterday FROM orders WHERE DATE(timedate) = DATE(NOW() - INTERVAL 2 DAY)
Following the advice of another answer I created the following, but that doesn't seem to work syntax-wise, and I'm not quite sure why. Is there another way to do this? I can't find a similar question on this
SELECT
SUM(IF(DATE(timedate) = DATE(NOW() - INTERVAL 1 DAY))) AS testcount1,
SUM(IF(DATE(timedate) = DATE(NOW() - INTERVAL 2 DAY))) AS testcount2
FROM
orders

You're missing the output values for the IF expression. Also you should use CURRENT_DATE() so you don't need to convert to a DATE:
SELECT
SUM(IF(DATE(timedate) = CURRENT_DATE() - INTERVAL 1 DAY, 1, 0)) AS testcount1,
SUM(IF(DATE(timedate) = CURRENT_DATE() - INTERVAL 2 DAY, 1, 0)) AS testcount2
FROM
orders
Note that MySQL treats boolean expressions as 1 (true) or 0 (false) in a numeric context, so you can actually SUM the expression without needing the IF:
SELECT
SUM(DATE(timedate) = CURRENT_DATE() - INTERVAL 1 DAY) AS testcount1,
SUM(DATE(timedate) = CURRENT_DATE() - INTERVAL 2 DAY) AS testcount2
FROM
orders

You want conditional aggregation. I would phrase the query as follows:
SELECT
SUM(
timedate >= CURRENT_DATE - INTERVAL 1 DAY
and timedate < CURRENT_DATE
) AS testcount1,
SUM(
timedate >= CURRENT_DATE - INTERVAL 2 DAY
and timedate < CURRENT_DATE- INTERVAL 1 DAT
) AS testcount2
FROM orders
Details:
this uses a nice feature of MySQL, that evaluates false/true conditions as 0/1 in numeric context
no date functions are applied on the timedate column : instead, we do litteral date comparisons. This is much more efficient, since the database can possibly take advantage of an index on the datetime column
You might also want to add a WHERE clause to the query:
WHERE
timedate >= CURRENT_DATE - INTERVAL 2 day
AND timedate< CURRENT_DATE

Related

Combine two SQL queries which use Date Intervals, Group and SUM

First off, thank you in advance.
I have 2 queries that I am working with as I would like to compare last week to the previous week...
Getting Last Week
SELECT keyword,
SUM(users_desktop) AS desktop_last_week
FROM js
WHERE country='US'
AND day >= curdate() - INTERVAL DAYOFWEEK(curdate())+6 DAY
AND day < curdate() - INTERVAL DAYOFWEEK(curdate())-1 DAY
GROUP BY keyword
ORDER BY desktop_last_week DESC
LIMIT 10;
Getting Previous Week
SELECT keyword,
SUM(users_desktop) AS desktop_previous_week
FROM js
WHERE country='US'
AND day >= curdate() - INTERVAL DAYOFWEEK(curdate())+12 DAY
AND day < curdate() - INTERVAL DAYOFWEEK(curdate())-7 DAY
GROUP BY keyword
ORDER BY desktop_previous_week DESC
LIMIT 10;
What I would like to do is combine these queries so that I can then ORDER BY the division of desktop_last_week/desktop_this_week to find keywords that are trending up (ie: searched a lot more this week than last week)
Any idea on how to combine these together?
This is called conditional aggregation. Use where clauses from your existing queries to do it.
SELECT keyword,
Sum(CASE
WHEN day >= Curdate() - INTERVAL Dayofweek(Curdate())+6 day
AND day < Curdate() - INTERVAL Dayofweek(Curdate())-1 day THEN
users_desktop
ELSE 0
end) AS desktop_last_week,
Sum(CASE
WHEN day >= Curdate() - INTERVAL Dayofweek(Curdate())+12 day
AND day < Curdate() - INTERVAL Dayofweek(Curdate())-7 day THEN
users_desktop
ELSE 0
end) AS desktop_prev_last_week
FROM js
WHERE country = 'US'
GROUP BY keyword
ORDER BY desktop_prev_last_week / desktop_this_week DESC
LIMIT 10
Use Union!
You can get 2 Queries to one with that. If you want to order that then put it into a subquery
You could expand the where clause to contain both time ranges and move the logic of differentiating between them to case expressions inside the sums. By the way, using the between operator instead of a >= and < pair would make the query itself a tad easier to read:
SELECT keyword,
SUM(CASE WHEN day BETWEEN
(CURDATE() - INTERVAL DAYOFWEEK(curdate()) + 6 DAY) AND
(CURDATE() - INTERVAL DAYOFWEEK(curdate()) - 1 DAY)
THEN users_desktop
END) AS desktop_last_week,
SUM(CASE WHEN day BETWEEN
(CURDATE() - INTERVAL DAYOFWEEK(curdate()) + 12 DAY) AND
(CURDATE() - INTERVAL DAYOFWEEK(curdate()) - 7 DAY)
THEN users_desktop
END) AS desktop_previous_week
FROM js
WHERE country = 'US'
GROUP BY keyword
ORDER BY desktop_last_week DESC, desktop_previous_week DESC
LIMIT 10;

How do I subtract two results from a SELECT statement within that statement?

This pulls back two int values of yesterday and today. I'd like to subtract the two results from within the statement in a third column called difference:
SELECT (
SELECT COUNT(*)
FROM collectors_users
WHERE DATE(dateadded) = CURDATE() - INTERVAL 1 DAY
) AS yesterday, COUNT(*) AS today
FROM collectors_users
WHERE DATE(dateadded) = CURDATE()
You need to repeat the expressions. SQL (in general) does not allow you to re-use column aliases in the same SELECT. You can simplify the logic to:
SELECT SUM(DATE(dateadded) = CURDATE() - INTERVAL 1 DAY) AS yesterday,
SUM(DATE(dateadded) = CURDATE()) as today,
(SUM(DATE(dateadded) = CURDATE()) -
SUM(DATE(dateadded) = CURDATE() - INTERVAL 1 DAY)
) as diff
FROM collectors_users
WHERE dateadded >= CURDATE() - INTERVAL 1 DAY AND
dateadded < CURDATE() + INTERVAL 1 DAY;
Note that the logic for the WHERE clause covers two days. Also, it does not use DATE(). This would allow the query to use an index, if available.

How to add date condition to my query?

I have this SQL statement. It works, and I need to add another one condition.
I need to sort it by date. occurence - is my date row.
SELECT dd.caption, COUNT(t.occurence)
FROM transaction t
INNER JOIN dict_departments dd
ON dd.id = t.terminal_id
GROUP BY dd.caption
How to add this condition:
WHERE t.occurence BETWEEN (CURRENT_DATE() - INTERVAL 1 MONTH)
to my query.
Try this:
WHERE t.occurrece BETWEEN current_date() AND dateadd(month,1,current_date())
The function dateadd is a SQL SERVER function, but the rest of the clause is standard SQL.
BETWEEN requires two arguments, a start point and an end point. If your end point is the current time, you have two options:
Using BETWEEN:
WHERE t.occurence BETWEEN (CURRENT_DATE() - INTERVAL 1 MONTH) AND NOW()
Using simple comparison operator:
WHERE t.occurence >= (CURRENT_DATE() - INTERVAL 1 MONTH)
If you want to filter dates from 1 month ago till now:
WHERE (t.occurrece BETWEEN DATE_ADD(CURDATE(), INTERVAL -1 MONTH) AND CURDATE()) = 1
or
WHERE (t.occurrece BETWEEN ADDATE(CURDATE(), INTERVAL -1 MONTH) AND CURDATE()) = 1

Combine 2 MySQL queries

I have this query
SELECT COUNT(*) from `login_log` where from_unixtime(`date`) >= DATE_SUB(NOW(), INTERVAL 1 WEEK);
and the same one with 1 diff. it's not 1 WEEK , but 1 MONTH
how can I combine those two and assign them to aliases?
I would do this with conditional aggregation:
SELECT SUM(from_unixtime(`date`) >= DATE_SUB(NOW(), INTERVAL 1 WEEK)),
SUM(from_unixtime(`date`) >= DATE_SUB(NOW(), INTERVAL 1 MONTH))
FROM `login_log`;
MySQL treats boolean values as integers, with 1 being "true" and 0 being "false". So, using sum() you can count the number of matching values. (In other databases, you would do something similar using case.)
Use the where condition with one month internal and add the same where condition with one week internal as a Boolean column return.
I mean
Select count (*) all_in_month, (from_unixtime(`date`) >= DATE_SUB(NOW(), INTERVAL 1 WEEK)) as in_week from `login_log` where from_unixtime(`date`) >= DATE_SUB(NOW(), INTERVAL 1 a MONTH) GROUP BY in_week;
P.s. haven't tested but afaik it should work
Even though it's pretty tough to understand what you ask:
If you want them in the same column use OR
SELECT COUNT(*) from 'login_log' where from_unixtime('date') >= DATE_SUB(NOW(), INTERVAL 1 WEEK) OR from_unixtime('date') >= DATE_SUB(NOW(), INTERVAL 1 MONTH) ;
If you don't want duplicate answers: use GROUP BY

How do I select between the 1st day of the current month and current day in MySQL?

I need to select data from MySQL database between the 1st day of the current month and current day.
select*from table_name
where date between "1st day of current month" and "current day"
Can someone provide working example of this query?
select * from table_name
where (date between DATE_ADD(LAST_DAY(DATE_SUB(CURDATE(), interval 30 day), interval 1 day) AND CURDATE() )
Or better :
select * from table_name
where (date between DATE_FORMAT(NOW() ,'%Y-%m-01') AND NOW() )
I was looking for a similar query where I needed to use the first day of a month in my query.
The last_day function didn't work for me but DAYOFMONTH came in handy.
So if anyone is looking for the same issue, the following code returns the date for first day of the current month.
SELECT DATE_SUB(CURRENT_DATE, INTERVAL DAYOFMONTH(CURRENT_DATE)-1 DAY);
Comparing a date column with the first day of the month :
select * from table_name where date between
DATE_SUB(CURRENT_DATE, INTERVAL DAYOFMONTH(CURRENT_DATE)-1 DAY) and CURRENT_DATE
select * from table_name
where `date` between curdate() - dayofmonth(curdate()) + 1
and curdate()
SQLFiddle example
I have used the following query. It has worked great for me in the past.
select date(now()) - interval day(now()) day + interval 1 day
try this :
SET #StartDate = DATE_SUB(DATE(NOW()),INTERVAL (DAY(NOW())-1) DAY);
SET #EndDate = ADDDATE(CURDATE(),1);
select * from table where (date >= #StartDate and date < #EndDate);
Complete solution for mysql current month and current year, which makes use of indexing properly as well :)
-- Current month
SELECT id, timestampfield
FROM table1
WHERE timestampfield >= DATE_SUB(CURRENT_DATE, INTERVAL DAYOFMONTH(CURRENT_DATE)-1 DAY)
AND timestampfield <= LAST_DAY(CURRENT_DATE);
-- Current year
SELECT id, timestampfield
FROM table1
WHERE timestampfield >= DATE_SUB(CURRENT_DATE, INTERVAL DAYOFYEAR(CURRENT_DATE)-1 DAY)
AND timestampfield <= LAST_DAY(CURRENT_DATE);
select * from table
where date between
(date_add (CURRENT_DATE, INTERVAL(1 - DAYOFMonth(CURRENT_DATE)) day)) and current_date;
select * from <table>
where <dateValue> between last_day(curdate() - interval 1 month + interval 1 day)
and curdate();
I found myself here after needing this same query for some Business Intelligence Queries I'm running on an e-commerce store. I wanted to add my solution as it may be helpful to others.
set #firstOfLastLastMonth = DATE_SUB(LAST_DAY(DATE_ADD(NOW(), INTERVAL -2 MONTH)),INTERVAL DAY(LAST_DAY(DATE_ADD(NOW(), INTERVAL -2 MONTH)))-1 DAY);
set #lastOfLastLastMonth = LAST_DAY(DATE_ADD(NOW(), INTERVAL -2 MONTH));
set #firstOfLastMonth = DATE_SUB(LAST_DAY(DATE_ADD(NOW(), INTERVAL -1 MONTH)),INTERVAL DAY(LAST_DAY(DATE_ADD(NOW(), INTERVAL -1 MONTH)))-1 DAY);
set #lastOfLastMonth = LAST_DAY(DATE_ADD(NOW(), INTERVAL -1 MONTH));
set #firstOfMonth = DATE_ADD(#lastOfLastMonth, INTERVAL 1 DAY);
set #today = CURRENT_DATE;
Today is 2019-10-08 so the output looks like
#firstOfLastLastMonth = '2019-08-01'
#lastOfLastLastMonth = '2019-08-31'
#firstOfLastMonth = '2019-09-01'
#lastOfLastMonth = '2019-09-30'
#firstOfMonth = '2019-10-01'
#today = '2019-10-08'
A less orthodox approach might be
SELECT * FROM table_name
WHERE LEFT(table_name.date, 7) = LEFT(CURDATE(), 7)
AND table_name.date <= CURDATE();
as a date being between the first of a month and now is equivalent to a date being in this month, and before now. I do feel that this is a bit easier on the eyes than some other approaches, though.
SELECT date_sub(current_date(),interval dayofmonth(current_date())-1 day) as first_day_of_month;
I had some what similar requirement - to find first day of the month but based on year end month selected by user in their profile page.
Problem statement - find all the txns done by the user in his/her financial year. Financial year is determined using year end month value where month can be any valid month - 1 for Jan, 2 for Feb, 3 for Mar,....12 for Dec.
For some clients financial year ends on March and some observe it on December.
Scenarios - (Today is `08 Aug, 2018`)
1. If `financial year` ends on `July` then query should return `01 Aug 2018`.
2. If `financial year` ends on `December` then query should return `01 January 2018`.
3. If `financial year` ends on `March` then query should return `01 April 2018`.
4. If `financial year` ends on `September` then query should return `01 October 2017`.
And, finally below is the query. -
select #date := (case when ? >= month(now())
then date_format((subdate(subdate(now(), interval (12 - ? + month(now()) - 1) month), interval day(now()) - 2 day)) ,'%Y-%m-01')
else date_format((subdate(now(), interval month(now()) - ? - 1 month)), '%Y-%m-01') end)
where ? is year end month (values from 1 to 12).
The key here is to get the first day of the month. For that, there are several options. In terms of performance, our tests show that there isn't a significant difference between them - we wrote a whole blog article on the topic. Our findings show that what really matters is whether you need the result to be VARCHAR, DATETIME, or DATE.
The fastest solution to the real problem of getting the first day of the month returns VARCHAR:
SELECT CONCAT(LEFT(CURRENT_DATE, 7), '-01') AS first_day_of_month;
The second fastest solution gives a DATETIME result - this runs about 3x slower than the previous:
SELECT TIMESTAMP(CONCAT(LEFT(CURRENT_DATE, 7), '-01')) AS first_day_of_month;
The slowest solutions return DATE objects. Don't believe me? Run this SQL Fiddle and see for yourself 😊
In your case, since you need to compare the value with other DATE values in your table, it doesn't really matter what methodology you use because MySQL will do the conversion implicitly even if your formula doesn't return a DATE object.
So really, take your pick. Which is most readable for you? I'd pick the first since it's the shortest and arguably the simplest:
SELECT * FROM table_name
WHERE date BETWEEN CONCAT(LEFT(CURRENT_DATE, 7), '-01') AND CURDATE;
SELECT * FROM table_name
WHERE date BETWEEN DATE(CONCAT(LEFT(CURRENT_DATE, 7), '-01')) AND CURDATE;
SELECT * FROM table_name
WHERE date BETWEEN (LAST_DAY(CURRENT_DATE) + INTERVAL 1 DAY - INTERVAL 1 MONTH) AND CURDATE;
SELECT * FROM table_name
WHERE date BETWEEN (DATE(CURRENT_DATE) - INTERVAL (DAYOFMONTH(CURRENT_DATE) - 1) DAY) AND CURDATE;
SELECT * FROM table_name
WHERE date BETWEEN (DATE(CURRENT_DATE) - INTERVAL (DAYOFMONTH(CURRENT_DATE)) DAY + INTERVAL 1 DAY) AND CURDATE;
SELECT * FROM table_name
WHERE date BETWEEN DATE_FORMAT(CURRENT_DATE,'%Y-%m-01') AND CURDATE;
I used this one
select DATE_ADD(DATE_SUB(LAST_DAY(now()), INTERVAL 1 MONTH),INTERVAL 1 day) first_day
,LAST_DAY(now()) last_day, date(now()) today_day
All the responses here have been way too complex. You know that the first of the current month is the current date but with 01 as the date. You can just use YEAR() and MONTH() to build the month date by inputting the NOW() method.
Here's the solution:
select * from table_name
where date between CONCAT_WS('-', YEAR( NOW() ), MONTH( NOW() ), '01') and DATE( NOW() )
CONCAT_WS() joins a series of strings with a separator (a dash in this case).
So if today is 2020-08-28, YEAR( NOW() ) = '2020' and MONTH( NOW() ) = '08' and then you just need to append '01' at the end.
Voila!
Get first date and last date from month and year.
select LAST_DAY(CONCAT(year,'.',month,'.','01')) as registerDate from user;
select date_add(date_add(LAST_DAY(end_date),interval 1 DAY),interval -1 MONTH) AS closingDate from user;
SET #date:='2012-07-11';
SELECT date_add(date_add(LAST_DAY(#date),interval 1 DAY),
interval -1 MONTH) AS first_day