I have a table:
ID | Name | Date
1 | ABC | 2015-01-01
2 | XYZ | 2015-01-02
3 | ABC | 2015-01-03
4 | ABC | 2015-01-04
I want to query this table such a way that the result becomes:
ID | Name | Date | NextDate
1 | ABC | 2015-01-01 | 2015-01-03
2 | XYZ | 2015-01-02 | null
3 | ABC | 2015-01-03 | 2015-01-04
4 | ABC | 2015-01-04 | null
One Solution is:
select t1.*,
(select min(t2.Date) from TAB t2 where t2.ID > t1.ID t2.Name = t1.Name) NextDate
from TAB t1
But this is very slow as we are doing aggregation on each row. Is there any alternative solution to this which is more efficient than above ?
For example, by using the LEAD() function, from the current row, you can access data of the next row, or the row after the next row, and so on. The LEAD() function can be very useful for comparing the value of the current row with the value of the following row.
To do this, use a transaction in which you execute the insert and then query for the id like: INSERT INTO table (col1) VALUES ("Text"); SELECT LAST_INSERT_ID(); The returnset now contains only one column which holds the id of the newly generated row.
If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL. Insert some records in the table using insert command.
An asterisk (" * ") can be used to specify that the query should return all columns of the queried tables. SELECT is the most complex statement in SQL, with optional keywords and clauses that include: The FROM clause, which indicates the table(s) to retrieve data from.
Since SQL SERVER 2008
does not support LEAD
window function we have to simulate it using row_number
and self join
. Try this
;WITH cte
AS (SELECT t1.*,
Row_number()
OVER(
partition BY Name
ORDER BY [Date]) AS rn
FROM TAB t1)
SELECT a.ID,a.Name,a.Date,b.Date as nextdate
FROM cte a
LEFT OUTER JOIN cte b
ON a.Name = b.Name
AND a.rn + 1 = b.rn ORDER BY a.ID
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With