Je suis tombé sur une table qui a une structure similaire à la variable @t ci-dessous.
Je veux trouver l'entrée finale pour chaque entrée de départ, mais cela devient difficile car les entrées peuvent contenir des sous-entrées.
Avez-vous une idée de la façon dont je pourrais trouver le EndEntryText pour le StartEntryText qui le parraine en utilisant sa position ?
Représentation visuelle des entrées :
-- Start 1
-- Start 2
-- Stop 2
-- Start 3
-- Start 4
-- Start 5
-- Stop 5
-- Stop 4
-- Stop 3
-- Stop 1
Sortie souhaitée :
StartEntryText EndEntryText
Start 1 Stop 1
Start 2 Stop 2
Start 3 Stop 3
Start 4 Stop 4
Start 5 Stop 5
SQL :
-- Simplified Table Structure
DECLARE @t TABLE (EntryText varchar(16) NULL
, EntryType varchar(16)
, EntryIndex int NULL
)
-- Test Data
INSERT INTO @t(EntryText, EntryType, EntryIndex)
SELECT d.EntryText
, d.EntryType
, d.EntryIndex
FROM
(
SELECT 'Start 1 ' AS EntryText, 1 AS EntryIndex, 'Open' AS EntryType
UNION ALL SELECT 'Start 2' AS EntryText, 2 AS EntryIndex, 'Open' AS EntryType
UNION ALL SELECT 'Stop 2' AS EntryText, 3 AS EntryIndex, 'Close' AS EntryType
UNION ALL SELECT 'Start 3' AS EntryText, 4 AS EntryIndex, 'Open' AS EntryType
UNION ALL SELECT 'Start 4' AS EntryText, 5 AS EntryIndex, 'Open' AS EntryType
UNION ALL SELECT 'Start 5' AS EntryText, 6 AS EntryIndex, 'Open' AS EntryType
UNION ALL SELECT 'Stop 5' AS EntryText, 7 AS EntryIndex, 'Close' AS EntryType
UNION ALL SELECT 'Stop 4' AS EntryText, 8 AS EntryIndex, 'Close' AS EntryType
UNION ALL SELECT 'Stop 3' AS EntryText, 9 AS EntryIndex, 'Close' AS EntryType
UNION ALL SELECT 'Stop 1' AS EntryText, 10 AS EntryIndex, 'Close' AS EntryType
) d
-- TODO: Find EndEntryText
SELECT t.EntryText AS StartEntryText
, NULL AS EndEntryText
FROM @t t
WHERE t.EntryType = 'Open'