Skip to content

Commit 2682105

Browse files
Update Advanced SQL Puzzles Solutions.sql
1 parent cb40e39 commit 2682105

1 file changed

Lines changed: 16 additions & 0 deletions

File tree

Advanced SQL Puzzles/Advanced SQL Puzzles Solutions.sql

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4052,6 +4052,21 @@ INSERT INTO #BatchLines (Batch, Line, Syntax) VALUES
40524052
('A', 6, 'GO');
40534053
GO
40544054

4055+
--Solution 1
4056+
--CTE with MIN
4057+
WITH cte_BatchLines_Go AS
4058+
(
4059+
SELECT *
4060+
FROM ##BatchLines
4061+
WHERE Syntax = 'GO'
4062+
)
4063+
SELECT a.Batch, a.BatchStart, MIN(b.Line) AS MinLine
4064+
FROM ##BatchStarts a LEFT JOIN
4065+
cte_BatchLines_Go b ON b.Line >= a.BatchStart AND a.Batch = b.Batch
4066+
GROUP BY a.Batch, a.BatchStart;
4067+
4068+
--Solution 2
4069+
--Correlated Subquery
40554070
SELECT a.*,
40564071
b.MinLine
40574072
FROM #BatchStarts a CROSS APPLY
@@ -4060,6 +4075,7 @@ FROM #BatchStarts a CROSS APPLY
40604075
WHERE b.Line >= a.BatchStart AND Syntax = 'GO' AND a.Batch = b.Batch) b;
40614076
GO
40624077

4078+
40634079
/*----------------------------------------------------
40644080
The End
40654081
*/----------------------------------------------------

0 commit comments

Comments
 (0)