+----------+--------------+-------------------------+
| ticketid | ticketpostid | date |
+----------+--------------+-------------------------+
| 1387935 | 3147808 | 2012-09-17 13:33:01 |
| 1387935 | 3147812 | 2012-09-17 13:33:41 |
| 1387938 | 3147818 | 2012-09-17 13:35:01 |
| 1387938 | 3148068 | 2012-09-17 13:37:01 |
| 1387938 | 3148323 | 2012-09-17 14:47:01 |
| 1387939 | 3147820 | 2012-09-17 13:36:01 |
| 1387939 | 3147834 | 2012-09-17 13:36:25 |
| 1387939 | 3147851 | 2012-09-17 13:41:01 |
| 1387939 | 3147968 | 2012-09-17 13:59:06 |
| 1387939 | 3147996 | 2012-09-17 14:03:01 |
This is a result of a query that I wrote. There are two and more than two rows with same ticketid. I need to find the time difference between first two date in each ticketid
Ex.
+----------+--------------+-------------------------+
| ticketid | ticketpostid | date |
+----------+--------------+-------------------------+
| 1387935 | 3147808 | 2012-09-17 13:33:01 |
| 1387935 | 3147812 | 2012-09-17 13:33:41 |
| 1387938 | 3147818 | 2012-09-17 13:35:01 |
| 1387938 | 3148068 | 2012-09-17 13:37:01 |
| 1387939 | 3147820 | 2012-09-17 13:36:01 |
| 1387939 | 3147834 | 2012-09-17 13:36:25 |
As a result;
+----------+--------------+
| ticketid |time diff(sec)|
+----------+--------------+
| 1387935 | 40 |
| 1387938 | 120 |
| 1387939 | 24 |
Can you tell me how I can do this?
Thanks.
For PostgreSQL, I think you want the
lagwindow function to compare the rows; it’ll be much more efficient than a self-join and filter. This won’t work with MySQL, as it still doesn’t seem to support the standard SQL:2003 window functions; see below.To find only the two lowest you can use the
dense_rankwindow function over theticketid, then filter the results to return only rows wheredense_rank() = 2, ie row with the second-from-lowest timestamp, wherelag()will produce the row with the lowest timestamp.See this SQLFiddle which shows sample DDL and output.
I’ve used
ticketdateas the name for the date column becausedateis a terrible name for a column (it’s a data type name) and should never be used; it has to be double quoted in many situations to work.The portable approach is probably the self-join others have posted. The window function approach above probably works on Oracle too, but doesn’t seem to in MySQL. As far as I can find out it doesn’t support the SQL:2003 window functions.
The schema definition will work with MySQL if you
SET sql_mode = 'ANSI'and usetimestampinstead oftimestamp with time zone. It seems the window functions won’t; MySQL chokes on theOVERclause. See this SQLFiddle.