Hi
I cannot seem to find a proper sql query for my problem.
Input: (small set)
TicketNr|CustomerKey|
11 | 1
11 | 2
22 | 1
22 | 3
33 | 4
33 | 5
44 | 6
55 | 7
66 | 7
77 | 8
88 | 8
88 | 9
Output:
CustomerKey|NewKey
1 | 1
2 | 1
3 | 1
4 | 2
5 | 2
6 | 3
7 | 4
8 | 5
9 | 5
Explanation :
One ticket can contain muliple customers. I want to create a new Key bases on all customers that can be linked to each other.
CustomerKey 1 is used in Tickets 11 and 12 so all customer keys connecting to these tickets must be converted to on. That means that CustomerKey's 1,2 and 3 are combined.
I have tried subqueries/Ranks/first_value but cannot seem to get it to work correctly
Test code if anyone is interested
Any help appreciated!
USE [TestDb] GO DROP TABLE [dbo].[InputTable] CREATE TABLE [dbo].[InputTable] ( [TicketNr] [int] NULL, [CustomerKey] [int] NULL ) ON [PRIMARY] INSERT INTO [dbo].[InputTable] ([TicketNr],[CustomerKey]) VALUES (11,1) INSERT INTO [dbo].[InputTable] ([TicketNr],[CustomerKey]) VALUES (11,2) INSERT INTO [dbo].[InputTable] ([TicketNr],[CustomerKey]) VALUES (22,1) INSERT INTO [dbo].[InputTable] ([TicketNr],[CustomerKey]) VALUES (22,3) INSERT INTO [dbo].[InputTable] ([TicketNr],[CustomerKey]) VALUES (33,4) INSERT INTO [dbo].[InputTable] ([TicketNr],[CustomerKey]) VALUES (33,5) INSERT INTO [dbo].[InputTable] ([TicketNr],[CustomerKey]) VALUES (44,6) INSERT INTO [dbo].[InputTable] ([TicketNr],[CustomerKey]) VALUES (55,7) INSERT INTO [dbo].[InputTable] ([TicketNr],[CustomerKey]) VALUES (66,7) INSERT INTO [dbo].[InputTable] ([TicketNr],[CustomerKey]) VALUES (77,8) INSERT INTO [dbo].[InputTable] ([TicketNr],[CustomerKey]) VALUES (88,8) INSERT INTO [dbo].[InputTable] ([TicketNr],[CustomerKey]) VALUES (88,9) GO