complain mysql queries to single query - mysql

I have 3 Queries
SELECT * FROM `admin_sprints`
where CURDATE() < `sprint_start_date` and
CURDATE() <`sprint_end_date` - retuen type as future
SELECT * FROM `admin_sprints`
where CURDATE() > `sprint_start_date` and
CURDATE() >`sprint_end_date` - retuen type as past
SELECT * FROM `admin_sprints`
where CURDATE() between `sprint_start_date` and
`sprint_end_date` - retuen type as current
i tried to combine this to single queries
So i tried
SELECT
*
FROM
admin_sprints
ORDER BY (CASE
WHEN sprint_start_date` and CURDATE() <`sprint_end_date` THEN future
ELSE admin_sprints` where CURDATE() > `sprint_start_date` and CURDATE() >`sprint_end_date then over
ELSE current
END);
admin_sprints
---------------|------------|-----------------|-----------------------
sprint_id |sprint_name |sprint_start_date| sprint_end_date |
1 Sprint1 2018-11-01 2018-11-13
2 sprint2 2018-11-14 2018-11-23
3 sprint 3 2018-11-24 2018-11-130
expected output
sprint_id sprint_name type
1 Sprint1 over
2 Sprint2 Active
3 Sprint3 future
I don't know method is correct or not.Bad luck it's not working.Any help would be appreciated

You need to use the CASE..WHEN statements in your SELECT clause, to determine the type accordingly. Try:
SELECT
*,
CASE WHEN sprint_start_date < CURDATE() AND
sprint_end_date < CURDATE()
THEN 'over'
WHEN CURDATE() BETWEEN sprint_start_date AND
sprint_end_date
THEN 'active'
ELSE 'future'
END AS type
FROM
admin_sprints

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 LAST_DAY() only reads 1 subquery result, how to process all results? using joins?

I have an insurance policies table like this:
+-------------------------------------------------------------+
| id | cancellation_val | cancellation_interval | expire_date |
+-------------------------------------------------------------+
| 1 | 30 | day | 2019-06-09 |
| 2 | 2 | month | 2019-12-01 |
+-------------------------------------------------------------+
I need to get the ids of the policies that are going to expire based on cancellation, from today and within 4 months, calculating the last day of the month, like this pseudo-code:
'today' <= LAST_DAY( expire_date - cancellation_val/interval ) < 'today + 4 months'
Being not a pro I think I should use JOINs but I don't know how, after days of trying the only thing I achieved was this:
SELECT LAST_DAY(
DATE_FORMAT(
STR_TO_DATE(
(SELECT CASE cancellation_interval
WHEN "day" THEN date_sub(expire_date, INTERVAL cancellation_val DAY)
WHEN "month" THEN date_sub(data_scadenzaexpire_date, INTERVAL cancellation_val MONTH)
END
AS newDate
FROM insurance WHERE id=2
), '%Y-%m-%d'
), '%Y-%m-%d'
)
)
This is working but I don't need the "WHERE id=2" clause (because I need to process ALL rows of the table), and if I remove it I got error "subquery returns more than 1 row".
So how I can proceed? And using the result to stay between 'today' AND 'today + 4 months' ?
I think with some kind of JOIN I could do it in a easier way but I don't know how.
Thank you all
The problem is the structure of the query, not the LAST_DAY function.
We want to return the id values of rows that meet some condition. So the query would be of the form:
SELECT t.id
, ...
FROM insurance t
WHERE ...
HAVING ...
Introducing another SELECT keyword basically introduces a subquery. There are restrictions on subqueries... in the SELECT list, a subquery can return a single column and (at most) a single row.
So let's ditch that extra SELECT keyword.
We can derive the newdate as an expression of the SELECT list, and then we can reference that derived column in the HAVING clause. The spec said we wanted to return the id value, so we include that in the SELECT list. We don't have to return any other columns, but for testing/debugging, it can be useful to return the values that were used to derive the newdate column.
Something like this:
SELECT t.id
, LAST_DAY(
CASE t.cancellation_interval
WHEN 'day' THEN t.expire_date - INTERVAL t.cancellation_val DAY
WHEN 'month' THEN t.expire_date - INTERVAL t.cancellation_val MONTH
ELSE t.expire_date
END
) AS newdate
, t.expire_date
, t.cancellation_interval
, t.cancellation_val
FROM insurance t
HAVING newdate >= DATE(NOW())
AND newdate <= DATE(NOW()) + INTERVAL 4 MONTH
ORDER
BY newdate ASC
We don't have to include the newdate in the SELECT list; we could just replace occurrences of newdate in the HAVING clause with the expression.
We could also use an inline view to "hide" the derivation of the newdate column
SELECT v.id
, v.newdate
FROM ( SELECT t.id
, LAST_DAY(
CASE t.cancellation_interval
WHEN 'day' THEN t.expire_date - INTERVAL t.cancellation_val DAY
WHEN 'month' THEN t.expire_date - INTERVAL t.cancellation_val MONTH
ELSE t.expire_date
END
) AS newdate
FROM insurance t
) v
WHERE v.newdate >= DATE(NOW())
AND v.newdate <= DATE(NOW()) + INTERVAL 4 MONTH
ORDER
BY v.newdate ASC
check this query: remove the HAVING Line to see all rows
SELECT
IF(cancellation_interval = 'day',
i.expire_date - INTERVAL i.`cancellation_val` DAY,
i.expire_date - INTERVAL i.`cancellation_val` MONTH
) as cancellation_day,
i.*
FROM `insurance` i
HAVING cancellation_day < NOW() + INTERVAL 4 MONTH;
SAMPLES
MariaDB [test]> SELECT IF(cancellation_interval = 'day', i.expire_date - INTERVAL i.`cancellation_val` DAY, i.expire_date - INTERVAL i.`cancellation_val` MONTH ) as cancellation_day, i.* FROM `insurance` i HAVING cancellation_day < NOW() + INTERVAL 4 MONTH;
+------------------+----+------------------+-----------------------+-------------+
| cancellation_day | id | cancellation_val | cancellation_interval | expire_date |
+------------------+----+------------------+-----------------------+-------------+
| 2019-05-10 | 1 | 30 | day | 2019-06-09 |
+------------------+----+------------------+-----------------------+-------------+
1 row in set (0.001 sec)
When you use a SELECT query as an expression, it can only return one row.
If you want to process all the rows, you need to call LAST_DAY() inside the query, not on the result.
SELECT *
FROM insurance
WHERE CURDATE() <= LAST_DAY(
expire_date - IF(cancellation_interval = 'day',
INTERVAL cancellation_val DAY,
INTERVAL cancellation_val MONTH))
AND LAST_DAY(expire_date - IF(cancellation_interval = 'day',
INTERVAL cancellation_val DAY,
INTERVAL cancellation_val MONTH)) < CURDATE + INTERVAL 4 MONTH

Mysql query problems (total amount of time)

I’m stuck..
I have the indicators on my heater connected to a raspberry pi. The pi then put the changed state (on and off) with the time into a mysql database.
Before I’ve used PHP to present the data but I’m now trying out Grafana. And I cant get the mysql query to present what I want.
I need to know how much time the heater has been activated (0/1) in the specified time range (typically the last 24h). And I need to take into account that the time range may start with ”0”, meaning that the heater has been on the time before that. And the same if it ends with ”1”.
And maybe also the percent of the day where it’s been activated.
Can someone please help me?
I'm looking for a result like this
+-------+--------------+--------------+
| value | secondsOfDay | PercentOfDay |
+-------+--------------+--------------+
| 0 | 28800 | 33.3 |
| 1 | 57600 | 66.6 |
+-------+--------------+--------------+
I've prepared:
http://sqlfiddle.com/#!9/556364a
Thanks!
To get the required data, you can use the following query:
NOTE: Depending on CURRDATE() the examples will fail. You can ofc. replace CURDATE() with a fixed value like 2018-11-27;
Explanation:
The query is joining the table with itself, taking into account, that on/off follows each other (L.id = R.id -1)
The query is selecting Any result, where "on" or "off" is today.
IF on was yesterday, the on-time is "corrected" to 00:00:00 of today: case when L.Time < CURDATE() then CURDATE() else L.Time end as onTime
IF the last entry is on, the off-time is "corrected" to 00:00:00 of tomorrow: COALESCE(R.time, CURDATE() + Interval 1 day) (note: You maybe want to use NOW() instead of CURDATE() + Interval 1 day, to have the current amount of seconds until "now")
The Same two methods are used to calculate the running seconds.
Query:
SELECT
L.playtime_id AS LID,
R.playtime_id AS RID,
case when L.Time < CURDATE() then CURDATE() else L.Time end as onTime,
COALESCE(R.time, CURDATE() + Interval 1 day) AS offTime,
(
UNIX_TIMESTAMP(COALESCE(R.time, CURDATE() + Interval 1 day)) -
UNIX_TIMESTAMP(case when L.Time < CURDATE() then CURDATE() else L.Time end)
) as RunningSeconds
FROM item0005 as L
LEFT JOIN item0005 AS R
ON L.playtime_id = R.playtime_id -1
WHERE
L.`value` = 1 AND
(
DATE(L.Time) = CURDATE() OR
DATE (R.Time) = CURDATE()
)
;
Result Example:
LID RID onTime offTime RunningSeconds
2 3 2018-11-27T09:00:00Z 2018-11-27T11:26:24Z 8784
4 5 2018-11-27T11:26:27Z 2018-11-27T11:28:29Z 122
6 7 2018-11-27T11:29:39Z 2018-11-27T11:39:55Z 616
8 (null) 2018-11-27T11:50:55Z 2018-11-28T00:00:00Z 43745
Example assuming 00:00:00 of tomorrow: http://sqlfiddle.com/#!9/20bc14/1
Example using NOW() to count up seconds if the last state is on: http://sqlfiddle.com/#!9/3c6227/1
If you just need the Aggregations out of this, you can use another Surrounding Select and calculate the Percentage by knowing a day has 86400 seconds:
SELECT
SUM(RunningSeconds) AS RunningSeconds,
SUM(RunningSeconds) / 86400 * 100 AS PercentageRunning
FROM (
...
) as temp;
http://sqlfiddle.com/#!9/20bc14/5
try this
SELECT VALUE, SUM(TIME_TO_SEC(TIMEDIFF(T2,T1))), 100*SUM(TIME_TO_SEC(TIMEDIFF(T2,T1)))/86400 FROM
(SELECT A.VALUE AS VALUE, COALESCE(B.TIME, TIMESTAMP(CURDATE()-2)) AS T1, A.TIME AS T2
FROM ITEM0005 A
LEFT JOIN ITEM0005 B
ON A.PLAYTIME_ID-1= B.PLAYTIME_ID
WHERE A.VALUE='0'
UNION
SELECT '1' AS VALUE, A.TIME AS T1, COALESCE(B.TIME, TIMESTAMP(CURDATE()-1)) AS T2
FROM ITEM0005 A
LEFT JOIN ITEM0005 B
ON A.PLAYTIME_ID= B.PLAYTIME_ID-1
WHERE A.VALUE='0') C
GROUP BY VALUE;

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 Add 2 Hours from Formatted Time

I need to know how to add 2 hours to the below 'Completed' timestamp.
Here is the Select statement
Select Tsk.task_id,Tsk.org_id,Tsk.completed,Tsk.assgn_acct_id,name
FROM tdstelecom.tasks As Tsk
WHERE Tsk.task_id = '11094836'
AND DATE(Tsk.completed) < CURDATE() AND DATE(Tsk.completed) >= DATE_SUB(CURDATE
(),INTERVAL 180 DAY)
Here are the results: 2012-08-22 14:18:14
Desired results: 2012-08-22 16:18:14
Your tag says mySQL, use the subtime(exp1,exp2) function SUBTIME(Tsk.completed, '02:00:00.000000') in your select should do the trick.
select Tsk.completed+interval 2 hour,Tsk.assgn_acct_id,name
FROM tdstelecom.tasks As Tsk
WHERE Tsk.task_id = '11094836'
AND DATE(Tsk.completed) < CURDATE() AND DATE(Tsk.completed) >= DATE_SUB(CURDATE
(),INTERVAL 180 DAY)