I am attempting to write a query that will take a date value and return a numerical value. What I plan to use this for is to track the days until an inspection is due. For example I will input the inspection expiration date into the database, then I want the query to return the value of days remaining until the inspection is due.
Thanks for the help. I am not that good with SQL. I know how to write basic queries but anything past that I really don't know what to do.
You can use timestampdiff() function to get the remaining days.
Lets say the expire date is 2014-10-31 and comparing with now you can get the days as
mysql> select timestampdiff(day,now(),'2014-10-31') as days ;
+------+
| days |
+------+
| 11 |
+------+
1 row in set (0.00 sec)
Related
I’m very new to SQL, so sorry for the noob question.
I was given a table to analyse and I want to find the days passed between all the dates launched and dates of the deadline in a new column I made called duration. Then I want to find the average of those days. What would be the command I write for that?
——————————————
Launched | Deadline | Duration|
——————————————-
Avg | Avg | Avg
That’s what I want to do/find. I don’t know how to start/write it.
Use datediff
select datelaunched, deadline, datediff(day, datelaunched, deadline)
union all
select avg(datelaunched), avg(deadline), avg(datediff(day, datelaunched, deadline))
I speculate that you want something like this:
select avg(timestampdiff(day, datelaunched, deadlined)) as avg_dur_days
from t;
I need to convert some TIMESTAMP fields to INT in our MySQL (InnoDB) DB. I realize that converting a TIMESTAMP to INT is unusual, but we still need to do it :)
It seems straight-forward enough to do, but there are some timezone and daylight saving errors.
I have a script that generates my SQL code per column. For example, it generates:
ALTER TABLE alarmLog ADD COLUMN started_tmp INT UNSIGNED;
UPDATE alarmLog SET started_tmp = UNIX_TIMESTAMP(started);
ALTER TABLE alarmLog DROP started;
alter TABLE alarmLog CHANGE started_tmp started INT UNSIGNED NULL DEFAULT 0;
If I compare the before and after data using select FROM_UNIXTIME(1291788036);, the result looks good.
The idea is then to change all the client-side software to convert to UTC and use that INT when storing it. When retrieving, that INT is converted to the current time zone.
But then the docs warn me about this scenario (daylight savings in CET):
mysql> SELECT UNIX_TIMESTAMP('2005-03-27 02:00:00');
+---------------------------------------+
| UNIX_TIMESTAMP('2005-03-27 02:00:00') |
+---------------------------------------+
| 1111885200 |
+---------------------------------------+
1 row in set (0.00 sec)
mysql> SELECT UNIX_TIMESTAMP('2005-03-27 03:00:00');
+---------------------------------------+
| UNIX_TIMESTAMP('2005-03-27 03:00:00') |
+---------------------------------------+
| 1111885200 |
+---------------------------------------+
1 row in set (0.00 sec)
How do API and OS's normally deal with daylight savings? I know my PC has its clock in UTC and in summer time, the OS adds two hours to it, and in winter time one. I assume it uses the UTC time to determine whether it's DST or not.
So, how do I deal with this? Is the only solution to add a field to the database to specify DST offset?
You don't need to store the time in INT's. MySQL's TIMESTAMP type does that anyway (it uses standard Unix timestamps to store the time) and they are always in UTC timezone.
You only need to set the session timezone and all TIMESTAMP columns will be converted from/to your zone when you update/select them.
You can set the zone at connect/initialization time once:
SET time_zone = '+10:00';
And then you can select/update the time in your zone directly
SELECT timestamp_column FROM table ...
I'm not very familiar with datetime libs but I guess they use the timezone you provided and the time in question to determine timezone and daylight savings offsets.
In the example you provided I think one of the values is actually invalid, because the clock is supposed to jump from 01:59:59 to 03:00:00 and 02:00:00 never actually happened. The UNIX_TIMESTAMP function probably returns the nearest second in that case.
If I do a query such as the following:
SELECT HOUR( TIMEDIFF('2012-08-12 02:25:00',
'2012-09-14 02:25:33') ) as result
the result is 792, even though I'm subtracting a past data from a future date.
If I remove HOUR() and do:
SELECT TIMEDIFF('2012-08-12 02:25:00',
'2012-09-14 02:25:33') as result
Then the value is -792:00:33. Therefore clearly HOUR() is converting -792 to 792. I've tried it with other dates and result is the same (always positive hour being returned).
The manual doesn't say anything about this behaviour.
Is this a bug, or is it a feature that I can rely on to be present on all recent mysql installations?
There's a way to get the positive hour and the negative hour. EXTRACT will get the negative one.
SELECT EXTRACT(HOUR FROM '-01:00:00'), HOUR('-01:00:00')
Will return:
-1 1
It seems that it's an expected behaviour (can't say if bug or feature).
See the example:
mysql> select hour('-23:00:00');
+-------------------+
| hour('-23:00:00') |
+-------------------+
| 23 |
+-------------------+
1 row in set (0.04 sec)
If you need to get the hour from there I'd recommend parsing the result (if possible, outside SQL)
I've exported a database (I need the data for a report) we have a 'start date' which is the start date of each project, but in MYSQL it isn't showing a date but instead a random number, it must say the date in some way because the tasks seem to go in order and the numbers change accordingly.
Can anybody tell me how to work out the date from the numbers, an example is below:
1337156712
and another:
1321443614
Any help will be great thanks!
OK I am using this PHP script to change the dates:
<?php
$TimeStamp = "1185422400";
$Time = date("m-d-Y", $TimeStamp);
echo $Time;
?>
Can somebody help me turn it into an array so I can include around 500 dates and convert them all at once?
Thanks
Ricky
Assuming your number is a Unix timestamp, FROM_UNIXTIME() will give you a formatted date you can use with DATETIME fields:
mysql> SELECT FROM_UNIXTIME(1321443614) AS time;
+---------------------+
| time |
+---------------------+
| 2011-11-16 11:40:14 |
+---------------------+
1 row in set (0.00 sec)
There are plenty of other time functions available, all of which are listed here.
those are unix timestamps. They are the number of seconds past since Jan 1, 1970. There are a variety of function calls you can user to turn them into dates :)
I will be right back with a way to do it :)
select from_unixtime(1321443614) as time
arg! someone beat me to it!
What's the best way to store a date value for which in many cases only the year may be known?
MySQL allows zeros in date parts unless the NO_ZEROES_IN_DATE sql mode is enabled, which isn't by default. Is there any reason not to use a date field where if the month and day may be zero, or to split it up to 3 different fields for year, month and day (year(4), tinyint, tinyint)?
A better way is to split the date into 3 fields. Year, Month, Day. This gives you full flexibility for storing, sorting, and searching.
Also, it's pretty trivial to put the fields back together into a real date field when necessary.
Finally, it's portable across DBMS's. I don't think anyone else supports a 0 as a valid part of a date value.
Unless portability across DBMS is important, I would definitely be inclined to use a single date field. If you require even moderately complex date related queries, having your day, month and year values in separate fields will become a chore.
MySQL has a wealth of date related functions - http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html. Use YEAR(yourdatefield) if you want to return just the year value, or the same if you want to include it in your query's WHERE clause.
You can use a single date field in Mysql to do this. In the example below field has the date data type.
mysql> select * from test;
+------------+------+
| field | id |
+------------+------+
| 2007-00-00 | 1 |
+------------+------+
1 row in set (0.00 sec)
mysql> select * from test where YEAR(field) = 2007;
+------------+------+
| field | id |
+------------+------+
| 2007-00-00 | 1 |
+------------+------+
I would use one field it will make the queries easier.
Yes using the Date and Time functions would be better.
Thanks BrynJ
You could try a LIKE operative. Such as:
SELECT * FROM table WHERE date_feield LIKE 2009;
It depends on how you use the resulting data. A simple answer would be to simply store those dates where only the year is known as January 1. This approach is really simple and allows you to aggregate by year using all the standard built in date functions.
The problem arises if the month or date is significant. For example if you are trying to determine the age of a record in days, weeks, months or if you want to show distribution across this smaller level of granularity. This problem exists any way, though. If you have some full dates and some with only a year, how do you want to represent them in such instances.