Case in MySql when calculated values are empty for a row - mysql

I've got a long MySql string that is intended to calculate a daily percentage of a certain value. However, if there is nothing for a specific day, it just skips that day and goes to the next one. I need it to spit out a "0" for the day that it usually skips. Thanks for your help!
SELECT day(timestamp), CASE when
round(count(w_comp_current_1+W_comp_current_2)*10/86400*100,1) as 'run_time2' iS NULL
then '0'
ELSE round(count(w_comp_current_1+W_comp_current_2)*10/86400*100,1) as 'run_time2' END
FROM location.db WHERE timestamp between subdate(curdate(), interval 1 month)
and curdate() AND (w_comp_current_1+w_comp_current_2) > 45
GROUP BY MONTH(Timestamp), DAY(Timestamp)
ORDER BY Timestamp
New query using calendar table:
Select date_format(calendar.timestamp,'%b-%e') as 'Month-Day', round(count(w_comp_current_1+W_comp_current_2)*10/86400*100,1) as 'run_time2' from calendar
Left Join courthouse on calendar.timestamp = courthouse.timestamp
WHERE calendar.timestamp between subdate(curdate(), interval 1 month) and curdate() and calendar.timestamp > '2013-10-03%' AND (w_comp_current_1+w_comp_current_2) > 45
GROUP BY MONTH(calendar.Timestamp), DAY(calendar.Timestamp) ORDER BY calendar.Timestamp

You have the alias for the case column twice and both times in the wrong place. It should only be given after the case's END statement:
SELECT day(TIMESTAMP), CASE
WHEN round(count(w_comp_current_1 + W_comp_current_2) * 10 / 86400 * 100, 1) IS NULL
THEN '0'
ELSE round(count(w_comp_current_1 + W_comp_current_2) * 10 / 86400 * 100, 1)
END AS 'run_time2'
FROM location.db
WHERE TIMESTAMP BETWEEN subdate(curdate(), interval 1 month) AND curdate()
AND (w_comp_current_1 + w_comp_current_2) > 45
GROUP BY MONTH(TIMESTAMP), DAY(TIMESTAMP)
ORDER BY TIMESTAMP

Related

Counting all rows in column with two different date conditions

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

mysql select between two dates has odd behavior

I am selecting all records between NOW() and specific X day interval and came across this odd behavior that I don't understand.
I am checking 24 hours into the future and 24 hours into the past:
select * from table where date between NOW() and NOW() + 1 interval day; //works
select * from table where date between NOW() and NOW() - 1 interval day; //no records
But if I reverse the between call:
select * from table where date between NOW() + 1 interval day AND NOW(); //no records
select * from table where date between NOW() - 1 interval day AND NOW(); //works
Why does one call into the future work, but the same call into the past not work?...and if I reverse between parameters, the opposite behavior happens - does not work 24 hours into the future but does work 24 hours into the past.
======================
Adding #TimBiegeleisen explanation below here written out:
date = '2018-05-30' ;
select * from table where date between NOW() and NOW() + 1 interval day;
= date >= '2018-05-30' AND 'date <= 2018-05-31'; //true
select * from table where date between NOW() and NOW() - 1 interval day; records
= date >= '2018-05-30' AND 'date <= 2018-05-29'; //false
AND
select * from table where date between NOW() + 1 interval day AND NOW();
= date >= '2018-05-31' AND date <= '2018-05-30' //false
select * from table where date between NOW() - 1 interval day AND NOW();
= date >= '2018-05-29' and date <= '2018-05-30'; //true
The BETWEEN operator is interpreted a certain way:
WHERE date BETWEEN a AND b
means this:
WHERE date >= a AND date <= b
So the following two queries are equivalent:
select * from table where date between NOW() and NOW() - interval 1 day;
select * from table where date >= NOW() and date <= NOW() - interval 1 day;
Hopefully you can see that in your second query the WHERE condition can never be true, because a date cannot simutaneously be greater than or equal to now and less than now minus one at the same time.
simply put,
For SQL:
WHERE x between a and b
meaning
x >= a
and
x <= b
therefore, we have a <= x <= b or a <= b
PS: it's just about math :)

MySQL Rolling Value - subquery with joined value

I am trying to do a single query over a period of a month. This is a working query:
SELECT AVG(days)
FROM (SELECT datediff(IF(MIN(date_end) = '0000-00-00', DATE(NOW()), MAX(date_end)), MIN(date_start)) AS days
FROM tenancies
WHERE deleted_at IS NULL AND date_start < DATE_SUB(NOW(), INTERVAL 1 MONTH)
GROUP BY tenancies.tenant_id)
I want to replace NOW() with a date.
I have another query:
SELECT calendar_date
FROM calendar_dates
WHERE calendar_date BETWEEN NOW() - INTERVAL 1 MONTH AND NOW()
This gets me all the dates I want. If I try to do a double-subquery it doesn't recognize the calendar_date:
SELECT calendar_date, (SELECT AVG(days)
FROM (SELECT datediff(IF(MIN(date_end) = '0000-00-00', DATE(calendar_date), MAX(date_end)), MIN(date_start)) AS days
FROM tenancies
WHERE deleted_at IS NULL AND date_start < DATE_SUB(calendar_date, INTERVAL 1 MONTH)
GROUP BY tenancies.tenant_id) d) AS days
FROM calendar_dates
WHERE calendar_date BETWEEN NOW() - INTERVAL 1 MONTH AND NOW()
Anyone have any suggestions?
I assume it does not recognize DATE(calendar_date) and DATE_SUB(calendar_date, INTERVAL 1 MONTH), If right, Your tenancies table should have a calendar_date field in itself, otherwise you need to join tenancies with calendar_dates table in the middle query too. Because thats a separate query.

What is REALLY inside that field?

In MYSQL I have a '0' inserted into a DATETIME field called DT.
making it a "0000-00-00 00:00:00".
I need to compare DT to NOW() and tell if the result is in the past or not.
Some dates have real values, and some dates have a '0' (as said get the "0000-00-00 00:00:00").
How can I check that column DT + INTERVAL 3 MONTH < NOW() ?
Thanks!
It seems like you just want to ignore the 0 dates, so you can simply filter out the 0 dates in your WHERE clause like this:
SELECT * FROM mytable
WHERE DT != '0000-00-00 00:00:00'
AND DATE_ADD(DT, INTERVAL 3 MONTH) < NOW()
Here's the optimized version of that query. You should try to put your functions on the right side of the criteria so that MySQL can utilize indexes:
SELECT * FROM mytable
WHERE DT != '0000-00-00 00:00:00'
AND DT < DATE_ADD(NOW(), INTERVAL -3 MONTH)
You can use the DATE_ADD() function to get what you are looking for:
SELECT * FROM mytable WHERE DATE_ADD(`DT`, INTERVAL 3 MONTH) < NOW();
This will return all columns where (DT + INTERVAL 3 MONTH) < NOW()

Query to get all rows from previous month

I need to select all rows in my database that were created last month.
For example, if the current month is January, then I want to return all rows that were created in December, if the month is February, then I want to return all rows that were created in January. I have a date_created column in my database that lists the date created in this format: 2007-06-05 14:50:17.
SELECT * FROM table
WHERE YEAR(date_created) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
AND MONTH(date_created) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
Here's another alternative. Assuming you have an indexed DATE or DATETIME type field, this should use the index as the formatted dates will be type converted before the index is used. You should then see a range query rather than an index query when viewed with EXPLAIN.
SELECT
*
FROM
table
WHERE
date_created >= DATE_FORMAT( CURRENT_DATE - INTERVAL 1 MONTH, '%Y/%m/01' )
AND
date_created < DATE_FORMAT( CURRENT_DATE, '%Y/%m/01' )
If there are no future dates ...
SELECT *
FROM table_name
WHERE date_created > (NOW() - INTERVAL 1 MONTH);
Tested.
Alternatively to hobodave's answer
SELECT * FROM table
WHERE YEAR(date_created) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
AND MONTH(date_created) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
You could achieve the same with EXTRACT, using YEAR_MONTH as unit, thus you wouldn't need the AND, like so:
SELECT * FROM table
WHERE EXTRACT(YEAR_MONTH FROM date_created) = EXTRACT(YEAR_MONTH FROM CURDATE() - INTERVAL
1 MONTH)
SELECT *
FROM yourtable
where DATE_FORMAT(date_created, '%Y-%m') = date_format(DATE_SUB(curdate(), INTERVAL 1 month),'%Y-%m')
This should return all the records from the previous calendar month, as opposed to the records for the last 30 or 31 days.
Even though the answer for this question has been selected already, however, I believe the simplest query will be
SELECT *
FROM table
WHERE
date_created BETWEEN (CURRENT_DATE() - INTERVAL 1 MONTH) AND CURRENT_DATE();
WHERE created_date >= DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 2 MONTH)), INTERVAL 1 DAY)
AND created_date <= DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 1 MONTH)), INTERVAL 0 DAY)
This worked for me (Selects all records created from last month, regardless of the day you run the query this month)
Alternative with single condition
SELECT * FROM table
WHERE YEAR(date_created) * 12 + MONTH(date_created)
= YEAR(CURRENT_DATE) * 12 + MONTH(CURRENT_DATE) - 1
select fields FROM table
WHERE date_created LIKE concat(LEFT(DATE_SUB(NOW(), interval 1 month),7),'%');
this one will be able to take advantage of an index if your date_created is indexed, because it doesn't apply any transformation function to the field value.
Here is the query to get the records of the last month:
SELECT *
FROM `tablename`
WHERE `datefiled`
BETWEEN DATE_SUB( DATE( NOW( ) ) , INTERVAL 1
MONTH )
AND
LAST_DAY( DATE_SUB( DATE( NOW( ) ) , INTERVAL 1
MONTH ) )
Regards
- saqib
if you want to get orders from last month, you can try using
WHERE MONTH(order_date) = MONTH(CURRENT_DATE()) -1
One more way to do this in:
MYSQL
select * from <table_name> where date_created >= DATE_ADD(NOW(), INTERVAL -30 DAY);
SELECT * FROM table
WHERE YEAR(date_created) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
AND MONTH(date_created) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)