Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
821 B
4
Indexable
-- Add a new column named 'Output'
ALTER TABLE your_table
ADD Output DATE;

-- Update the 'Output' column with the calculated values
WITH RankedRows AS (
    SELECT
        id,
        name,
        age,
        city,
        country,
        fromdate,
        todate,
        ROW_NUMBER() OVER (PARTITION BY age, city, country ORDER BY fromdate) AS rn
    FROM your_table
)

UPDATE your_table
SET Output = CASE
                WHEN EXISTS (
                    SELECT 1
                    FROM RankedRows t2
                    WHERE t2.age = your_table.age
                        AND t2.city = your_table.city
                        AND t2.country = your_table.country
                        AND t2.rn = 2
                )
                THEN DATEADD(day, -1, todate)
                ELSE todate
            END;