I have a scenario where I'm trying to identify the changes made in fields over the months. If we identify the change, only the row with the latest data should be displayed along with a Changeflag for that column.
In other words, identifying what field values were updated.
CREATE TABLE [dbo].[TestChange](
[ID] [int] NULL,
[InTime] [date] NULL,
[dept] [varchar](100) NULL,
[Manager] [varchar](100) NULL,
[Budget] [int] NULL
) ON [PRIMARY]
GO
INSERT [dbo].[TestChange] ([ID], [InTime], [dept], [Manager], [Budget]) VALUES (101, CAST(N'2021-08-29' AS Date), N'Dept1', N'Manager1', 100000)
GO
INSERT [dbo].[TestChange] ([ID], [InTime], [dept], [Manager], [Budget]) VALUES (101, CAST(N'2021-09-29' AS Date), N'Dept1', N'Manager2', 200000)
GO
INSERT [dbo].[TestChange] ([ID], [InTime], [dept], [Manager], [Budget]) VALUES (102, CAST(N'2021-08-29' AS Date), N'Dept2', N'Manager1', 105000)
GO
INSERT [dbo].[TestChange] ([ID], [InTime], [dept], [Manager], [Budget]) VALUES (102, CAST(N'2021-09-29' AS Date), N'Dept2', N'Manager2', 220000)
GO
INSERT [dbo].[TestChange] ([ID], [InTime], [dept], [Manager], [Budget]) VALUES (103, CAST(N'2021-08-29' AS Date), N'Dept3', N'Manager1', 100000)
GO
INSERT [dbo].[TestChange] ([ID], [InTime], [dept], [Manager], [Budget]) VALUES (103, CAST(N'2021-09-29' AS Date), N'Dept3', N'Manager1', 150000)
GO
What I have tried:
with Ctetest as(
select t1.ID, t1.InTime,t1.dept,t1.Manager,t1.Budget, ROW_NUMBER() over(partition by t1.id order by t1.intime desc) as rownum
from TestChange t1
inner join TestChange t2
on t1.ID=t2.ID
where t1.Manager<>t2.Manager or t1.Budget<>t1.Budget
)
select * from ctetest where rownum=1
This gets the latest record, but doesn't say which record was updated from the previous month and what would be the right approach if there would be like 100 column which needs to be compared.