Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the next value within a table based on certain criteria

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 ?

like image 236
Tamal Kanti Nath Avatar asked Dec 24 '15 09:12

Tamal Kanti Nath


People also ask

How do I find the next row value in SQL?

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.

How do I get next available ID in SQL?

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.

How do I get the last inserted value in SQL?

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.

What does SELECT * from table mean?

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.


1 Answers

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
like image 185
Pரதீப் Avatar answered Nov 10 '22 07:11

Pரதீப்