MySQL getting time in specific offset - mysql

SELECT (from_time user_offset) as start FROM `availabilities`;
I am trying to add current logged in user's timezone offset to the time column values I am fetching.
The value of from_time will be like 02:30:00
and value of offset will like +02:00
Does anybody know what would be appropriate approach for the same.
UPDATE:
I tried the following way:
SELECT id, TIME_FORMAT( (
TIME_FORMAT( from_time, '%H:%i' ) + '05:30' ) , '%H:%i'
) AS
START
FROM `availabilities`;
I got 00:00, but the value should have been 02:00, as the value of from_time is 20:30
I even tried
SELECT
id,
CONVERT_TZ(
from_time,
'+00:00',
'+05:30'
) AS `start`
FROM availabilities
But it works only if **from_time field has both date and time, for time it returns null**

Converting timezones its not just adding +/-X hours.
It certainly should be more complex thing if you wants proper results.
I believe somthing like this may help
SELECT
id,
SUBSTRING(CONVERT_TZ(
CONCAT('2000-01-01 ', from_time),
time_format(TIMEDIFF(NOW(), UTC_TIMESTAMP), '+%H:%i'),
user_offset
), 12, 5) AS `start`
FROM availabilities

Related

MySql - Calculating distance in time using 2 values from 1 column (Poor design workaround)

I was granted access to a legacy database in order to do some statistics work.
I've so far gotten everything I need out of it, except I am trying to calculate a distance in time, using 5 values, stored in 4 columns (ARGGGHHH)
Above is a subsection of the database.
As you can see, I have start and stop date and time.
I would like to calculate the distance in time from str_date + str_time to stp_date + stp_time
The issue I have is, the calculation should be performed differently depending on the second value in stp_time.
IFF second value = "DUR".... THen I can just take the first value "01:04:51" in this scenario
IFF second value = anything else. stp_time represents a timecode and not a duration. This must then calculate stp_time - str_time (accounting for date if not same date)
All data is 24 hour format. I have done work with conditional aggregation, but I have not figured this one out, and I have never worked with a malformed column like this before.
Any and all advice is welcome.
Thanks for reading
SELECT
CASE WHEN RIGHT(stp_time,3)="DUR"
THEN
TIMEDIFF(LEFT(stp_time,8), '00:00:00')
ELSE
TIMEDIFF(
STR_TO_DATE(CONCAT(stp_date," ",LEFT(stp_time,8)), '%d/%b/%Y %H:%i:%s'),
STR_TO_DATE(CONCAT(str_date," ",LEFT(str_time,8)), '%d/%b/%Y %H:%i:%s')
)
END AS diff
FROM so33289063
Try this out, you might want a where condition for the subquery
With left and right:
SELECT IF(dur,stp,timediff(str,stp)) FROM(
SELECT STR_TO_DATE(CONCAT(str_date," ",LEFT(str_time,8)), 'd%/%b/%Y %H:%i:%s') as str,
STR_TO_DATE(CONCAT(stp_date," ",LEFT(stp_time,8)), 'd%/%b/%Y %H:%i:%s') as stp,
if(RIGHT(stp_time,3)="DUR",1,0) as dur
FROM my_table
) AS times

Date formatiing not working , mysql

I want to compare event filed of my table with current date. I have dates in event column in m/d/Y format i.e "09/24/2015" .
I am using this query for fetching result which get the records of current date but its returning empty result. I have a record for current date. what is wrong in it ?
SELECT *
FROM all_tasks
WHERE DATE_FORMAT( CURDATE( ) , '%d/%m/%Y' ) = DATE_FORMAT( date( event ) , '%d/%m/%Y' )
Assuming that you store the event as some sort of string, you can just do simply something like:
select * from all_tasks where DATE_FORMAT(NOW(),'%m/%d/%Y') = all_tasks.event
Here you go a fiddle sample.

MySQL: Using SQL having trouble figuring out the busiest hour for each day that has the maximum "in_bytes"?

Goal: Write the correct SQL to solve the problems below.
Part 1:
Having trouble figuring out the SQL statement on how to get the timestamp that includes the date and the hour where you have the maximum "in_bytes" for each day. See "video_hourly" table DDL code below. If there are two maximum values that have the same value in a given day just pick the first one. This data is being graphed in highcharts so there can only be one data point for each given day. You can fill the table with some sample data.
Part 2:
Another part of this problem is once you have all of the unique maximum "in_bytes" for each day then you need to sum the "in_bytes" and "out_bytes" to get one record.
To convert the UTC time from the database to local time we using this in the queries:
SELECT time_stamp,CONVERT_TZ(time_stamp, '+00:00', '-07:00' ) as localtime
Here is the DDL SQL for the table:
CREATE TABLE video_hourly (
id bigint(20) NOT NULL AUTO_INCREMENT,
time_stamp datetime NOT NULL,
in_bytes bigint(20) UNSIGNED NOT NULL DEFAULT 0,
out_bytes bigint(20) UNSIGNED NOT NULL DEFAULT 0,
opt_pct decimal(11, 2) NOT NULL DEFAULT 0.00,
PRIMARY KEY (id)
)
ENGINE = INNODB;
Any help or advice on this would greatly be appreciated. Thank you!
See this list of datetime functions that you can use. Specifically, you can use HOUR() to get the hour value.
You can also use DATE() to get the date part of a datetime column. Once you have those, you can group them together. I will try and break it down for you.
This will return the date, hour, and the in_bytes for that hour, by grouping by day and hour.
SELECT DATE(time_stamp) AS date, HOUR(time_stamp) AS hour, SUM(in_bytes) AS totalInBytes
FROM video_hourly
GROUP BY date, hour
ORDER BY date, hour, totalInBytes DESC;
This will also but the max totalInBytes at the top of each group because it orders by that in descending order.
Also, please see this question for how to get the max value in a group, which in this case is you want to get the max inBytes for each date.
Then, you can change your query to this:
SELECT CONCAT(v.date, ' ', v.hour) AS dateAndHour, v.totalInBytes
FROM(SELECT time_stamp AS fullDate, DATE(time_stamp) AS date, HOUR(time_stamp) AS hour, SUM(in_bytes) AS totalInBytes
FROM video_hourly
GROUP BY date, hour
ORDER BY date, hour, totalInBytes DESC
) v
WHERE(
SELECT COUNT(*)
FROM(SELECT DATE(time_stamp) AS date, HOUR(time_stamp) AS hour, SUM(in_bytes) AS totalInBytes
FROM video_hourly
GROUP BY date, hour
ORDER BY date, hour, totalInBytes DESC
) vh
WHERE vh.date = v.date AND vh.totalInBytes >= v.totalInBytes
) <= 1;
I can't try it without any sample data, but here is an SQL Fiddle link, if you want to try it out. I used this to make sure it would not produce any errors.

How to check if selected date range is between another date range

I am in the situation where i want to match a date range with another date range, it might be simple but i am stuck at it.
Below is table structure
Table - lifecycles
life_id
life_start_date
life_end_date
then a few records as below
1 - 07/23/2013 - 07/24/2013
2 - 07/15/2013 - 07/25/2015
3 - 03/10/2013 - 03/10/2014
Now i want to search these records by date range and want to see if some life exists in that range; e.g. i want to find the lives between 08/01/2013 - 01/01/2014
As expected result it should select the life#2 and life#3
How can this be done with MySQL query?
Any help is highly appreciated.
This query should do it:
SELECT
*
FROM
lifecycles
WHERE
str_to_date(life_start_date, '%m/%d/%Y') <= '2014-01-01'
AND str_to_date(life_end_date, '%m/%d/%Y') >= '2013-08-01';
Which basically means life hasn't started before the end of the range you are looking for, and life didn't end before the range start.
Since you keep dates in VARCHAR format, you need to use str_to_date function, which is bad since MySQL won't be able to utilize any possible indexes you have on start_date or end_date columns.
This might help you.
SELECT SUM( IF( '2014-01-02' BETWEEN from_date AND to_date, 1, 0 ) ) AS from_exist,
SUM( IF( '2014-02-12' BETWEEN from_date AND to_date, 1, 0 ) ) AS to_exist
FROM date_range
So based on the results you can check whether date is between existing date range or not.
So you want to exclude lifes that are ended BEFORE 08/01/2013 and the ones that are not started AFTER 01/01/2014. This should work:
SELECT *
FROM lifecycles as alive
WHERE NOT EXISTS (
SELECT 1
FROM lifecycles as dead
WHERE dead.life_id = alive.life_id
AND (str_to_date(life_start_date, '%m/%d/%Y') > '2014-01-01'
OR str_to_date(life_end_date, '%m/%d/%Y') < '2013-08-01'))

How to solve this "cursor" type query in MySQL?

I have the following data in my table. BTW ... this is a DD/MM/YYYY format:
Date
18/09/2012
17/09/2012
13/09/2012
11/09/2012
10/09/2012
09/09/2012
25/08/2012
24/08/2012
The result what I want are:
Date
18/09/2012
13/09/2012
11/09/2012
09/09/2012
25/08/2012
The rule:
It starts from the latest date (18/09/2012) and check the next one down (17/09/2012). If there is a date then removed that from the list because it requires to have 1 day apart. Then goes to 13/09/2012 and then check 12/09/2012 and didn't find and then move to next one so on and so on. Basically you can't have date close each other (min 1 day apart).
Now I can do this on cursor if it's on TSQL however since I'm working on MySQL, is there any such thing in MySQL? Or perhaps any sub-queries approach that can solve this query?
I'm appreciated your feedback.
Try this solution -
SELECT date FROM (
SELECT
date, #d := IF(#d IS NULL OR DATEDIFF(#d, date) > 1, date, #d) start_date
FROM
dates,
(SELECT #d:=null) t
ORDER BY
date DESC
) t
WHERE start_date = date
The subquery finds out start days (18, 13, 11...), then WHERE condition filters records. Try to run the subquery to understand how it works -
SELECT
date, #d := IF(#d IS NULL OR DATEDIFF(#d, date) > 1, date, #d) start_date
FROM
dates,
(SELECT #d:=null) t
ORDER BY
date DESC
SELECT
"MyTable1"."Date"
FROM
"MyTable" AS "MyTable1"
LEFT JOIN "MyTable" AS "MyTable2" ON
ADDDATE("MyTable1"."Date", INTERVAL 1 DAY) = "MyTable2"."Date"
WHERE
"MyTable2"."Date" IS NULL
ORDER BY
"MyTable1"."Date" DESC
As long as I know about mysql query will be quit tricky and buggy if some how you manage to write the one. I suggest go for cursor, here is the syntax of the cursor,
here is the syntax of the cursor