简体   繁体   中英

How can I create new column in sql based on previous date?

Col A         
1 Jan
2 Jan
3 Jan
5 Jan
6 Jan

Output

Col A      Col B
1 Jan    NULL
2 Jan    1 Jan
3 Jan    2 Jan
5 Jan    3 Jan
6 Jan    5 Jan

You can try with LAG() as suggested by @Akina

WITH D AS (
SELECT A FROM YOUR_TABLE 
) 
SELECT A, LAG(A, 1) OVER(ORDER BY A DESC)
FROM D

EDIT i see you are in mysql just now, you can try with this answer as well

Use the window function LAG() .

SELECT *,
  LAG(col_a) OVER (ORDER BY col_a)
FROM t;

Demo: db<>fidldle

WITH D AS ( SELECT date FROM table ) SELECT date, LAG(date, 1) OVER(ORDER BY date) FROM D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM