I have a scenario where IF ID
, Code
and InsertDate
is same and if it is 1st entry then it will be 0 else 1.
Demo data:
CREATE TABLE #test
(
ID int,
code int,
InsertDate datetime2
)
Insert into #test values (1,1,'2019-09-17 03:19:00.0000000')
Insert into #test values (1,1,'2019-09-17 03:19:00.0000000')
Insert into #test values (1,1,'2019-09-17 03:19:00.0000000')
Insert into #test values (2,1,'2019-09-17 03:19:00.0000000')
Insert into #test values (3,1,'2019-09-17 03:19:00.0000000')
Expected o/p
ID code InsertDate flag
-----------------------------------------
1 1 2019-09-17 03:19:00.0000000 0
1 1 2019-09-17 03:19:00.0000000 1
1 1 2019-09-17 03:19:00.0000000 1
2 1 2019-09-17 03:19:00.0000000 0
3 1 2019-09-17 03:19:00.0000000 0
What I tried
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY ID, Code, Insertdate ORDER BY InsertDate) flag
FROM #test
With this I got the initial logic but what to do next I need help.
A simple CASE
expression may help:
SELECT
*,
CASE
WHEN ROW_NUMBER() OVER (PARTITION BY ID, Code, Insertdate ORDER BY InsertDate) = 1 THEN 0
ELSE 1
END AS Flag
FROM #test