Hello
Given the below sample table and data, I am after a SQL script that can generate the sample output shown.
In a nutshell, I need to identify in a derived column, compared to the previous month, what's:
1) Not changed (e.g. 'A' in Feb)
2) Been removed (e.g. 'B' in Feb)
3) Been added (e.g. 'D' in Feb)
Can someone help with this? From what I remember Windows function would be ideal for this but it has been a long time since I used them...
CREATE TABLE [dbo].[Data]( [MyDate] [date] NOT NULL, [MyText] [varchar](10) NOT NULL ) ON [PRIMARY] GO -- Jan INSERT INTO [dbo].[Data](MyDate,MyText) VALUES ('01Jan2014', 'A') INSERT INTO [dbo].[Data](MyDate,MyText) VALUES ('01Jan2014', 'B') INSERT INTO [dbo].[Data](MyDate,MyText) VALUES ('01Jan2014', 'C') -- Feb - 'B' dropped, 'D' added INSERT INTO [dbo].[Data](MyDate,MyText) VALUES ('01Feb2014', 'A') INSERT INTO [dbo].[Data](MyDate,MyText) VALUES ('01Feb2014', 'C') INSERT INTO [dbo].[Data](MyDate,MyText) VALUES ('01Feb2014', 'D') -- Mar - 'A' and 'C' dropped, 'E' and 'F' added INSERT INTO [dbo].[Data](MyDate,MyText) VALUES ('01Mar2014', 'D') INSERT INTO [dbo].[Data](MyDate,MyText) VALUES ('01Mar2014', 'E') INSERT INTO [dbo].[Data](MyDate,MyText) VALUES ('01Mar2014', 'F') /* Sample required output MyDate MyText State 2014-01-01 A 0 2014-01-01 B 0 2014-01-01 C 0 2014-02-01 A 0 2014-01-01 B -1 2014-02-01 C 0 2014-02-01 D 1 2014-02-01 A -1 2014-02-01 C -1 2014-03-01 D 0 2014-03-01 E 1 2014-03-01 F 1 */