Time diff calculations where date and time are in seperate columns - datetime

I've got a query where I'm trying to get the hours in duration (eg 6.5 hours) between two different times.
In my database, time and date are held in different fields so I can efficiently query on just a startDate, or endDate as I never query specifically on time.
My query looks like this
SELECT COUNT(*), IFNULL(SUM(TIMEDIFF(endTime,startTime)),0) FROM events WHERE user=18
Sometimes an event will go overnight, so the difference between times needs to take into account the differences between the dates as well.
I've been trying
SELECT COUNT(*), IFNULL(SUM(TIMEDIFF(CONCAT(endDate,' ',endTime),CONCAT(startDate,' ',startTime))),0) FROM events WHERE user=18
Unfortunately I only get errors when I do this, and I can't seem to combine the two fields into a single timestamp.

Pretty sure your problem is that your concatenated values are being sent to TIMEDIFF() as strings rather than DATETIMEs. Try calling the DATETIME function on them:
SELECT COUNT(*), IFNULL(SUM(TIMEDIFF(DATETIME(CONCAT(endDate,' ',endTime)),DATETIME(CONCAT(startDate,' ',startTime)))),0) FROM events WHERE user=18
I don't have a MySQL DB in front of my to test that, but I think that or some similar form of it is what you are looking for. There's an example of it in the MySQL docs involving MICROSECOND:
http://dev.mysql.com/doc/refman/5.0/en/datetime.html
Edit: Hmm... looks like TIMEDIFF is supposed to work with strings. Worth trying anyway.

TIMEDIFF(endDate,startDate) + TIMEDIFF(endTime,startTime)

Related

How to select multiple series from a certain timestamp in SQLite Query

I have an SQLite database containing event log records with a timestamp and the event details. Some of these events are alarms generated by the system. What I need to do can be best explained in the following pseudo code:
for each event where type="alarm" get preceeding events between event.timestamp - 1 hour and event.timestamp
What I do now is query the database once to find the timestamp of each alarm and then loop over the result to get all the time periods for each alarm. This creates a list of transactions that I want to use for association rule mining but I feel that leaving SQL to then come back to it in a loop is inefficient. I've searched for answers to this question but I think I can't find the right keywords to search for.
I've edited the question as it wasn't as clear as I myself thought
Perhaps a self-join?
SELECT {column list}
from events e1, events e2
where e1.type="alarm"
and e2.time between (date(e1.time),'-1 hour') and e1.time

SSIS Merge Join by closest time

I have multiple datasources. After many transformations, I end with something like this:
Datasource1
StationId: Id integer
OriginDate: Datetime (i.e. 2011-04-25 16:53:26.623)
I have transformed this component to get separated the Year, the month and the day, doing so like this:
(DT_I2)YEAR(OriginDate)
and the same for the month using MONTH(OriginDate) and the Day.
On the other hand I also have the Time using (DT_DBTIME)OriginDate
I made those transformations because I think they may be useful for my question but not sure about it.
This datasource come from MSSQL
Datasource2
CurrentDate (i.e. 01/04/2011)
StationId: Integer
Hour (i.e. 01:59)
note that in this ds both fields are varchar.
This datasource comes from MySQL
What I need is to join this two datasets by the same stationId (easy) and for the closest date (not easy). I should get for each row in Datasource1 the row with the closest time in the other datasource, I mean, for the same Date, the closest time. This is because the datasource2 are measures at a given time, and the datasource1 are events at a given time, and I need to relate them.
How can I achieve this ? The Merge join component only allows to join by equals expressions. I would like to avoid staging if possible.
I thought on separate the hour and minutes from both datasources and compare them, and also compare for equality in dates and stationId, but I am not exactly sure how to accomplish the first part of that.
I am stucked with this, about which approach to take.

Compare time only in sql database (asp.net)

i wanna compare time and show records that are greater than the spcified time. For example in my database I have a field "TimeDate" where I store date and time together. Now i want to show records that are only greater than lets say this time "19/04/2012 2:34:27 PM". Is there anyway I can achieve this.
I have started with this code.
Select * from Table where TimeDate > '19/04/2012 2:34:27 PM'.
First of all the datatype is datetime in sql,
your sample code is right.
I am sure that sql is intelligent enough, for your current query.

ASP.NET / SQL drop-down list sort order

I am trying to correct the sort order of my ASP.NET drop down list.
The problem I have is that I need to select a distinct Serial number and have these numbers organised by DateTime Desc.
However I cannot ORDER BY DateTime if using DISTINCT without selecting the DateTime field in my query.
However if I select DateTime this selects every data value associated with a single Serial number and results in duplications.
The purpose of my page is to display data for ALL Serials, or data associated to one serial. When a new cycle begins (because it is a new production run) the Serial reverts to 1. So I cannot simply organise by serial number either.
When I use the following SQL statement the list box is in the order I require but after a period of time (usually a few hours) the order changes and appears to have no organised structure.
alt text http://img7.imageshack.us/i/captureky.jpg/
I'm fairly new to ASP.NET / SQL, does anyone know of a solution to my problem.
If you have multiple date times for each serial number, then which do you want to use for ordering? If the most recent, try this:
SELECT SerialNumber,
MAX(DateTimeField)
FROM Table
GROUP BY SerialNumber
ORDER BY 2 DESC
I don´t know if everybody agrees with that, but when I see a DISTINCT in a query the first thought that goes trough my mind is "This is wrong". Generally, DISTINCT is not necessary and it´s used when the person writing the query doesnt know very well what he is doing and this might be the case since you said you are new with Sql.
Without complete knowledge of your model is difficult to assist you a hundred percente, but I would say that you should use a GROUP BY clause instead of DISTINCT, then you can order it correctly.

How to store and get datetime value in SQLite

My table contains Birthdate field which has datatype as datetime.
I want to get all records having birthday today.
How can I get it?
Try this query:
SELECT * FROM mytable
WHERE strftime('%m-%d', 'now') = strftime('%m-%d', birthday)
Having a special datetime type has always seemed like unnecessary overhead to me, integers are fast, flexible, and use less space.
For general datetime values use Unix Epoch timestamps. Easy to work with, extremely flexible, as well as timezone (and even calender!) agnostic. (I recently wrote an article on using them, which I really have to plug...)
That said, if you're only interested in dates in the Gregorian calendar you may want to use a large integer in the following format: YYYYMMDD, eg 19761203. For you particular usage you could even create a four digit integer like MMDD, say 1703 — that's got to result in fast selects!
SQLite has very poor support for storing dates. You can use the method suggested by Nick D above but bear in mind that this query will result in full table scan since dates are not indexed correctly in SQLite (actually SQLite does not support dates as a built-in type at all).
If you really want to do a fast query then you'll have to add a separate (integral) column for storing the birth day (1-31) and attach an index for it in the database.
If you only want to compare dates then you can add a single (INTEGER) column that will store the date UTC value (but this trick won't allow you to search for individual date components easily).
Good Luck

Resources