Skip to content

Commit ed2bfa5

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

1 file changed

Lines changed: 55 additions & 1 deletion

File tree

Advanced SQL Puzzles/Advanced SQL Puzzles Solutions.sql

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1507,7 +1507,9 @@ GO
15071507
Answer to Puzzle #28
15081508
Fill the Gaps
15091509
1510-
This is often called a Flash Fill or a Data Smudge
1510+
This is often called a Flash Fill or a Data Smudge.
1511+
1512+
Tags: Flash Fill, Data Smudge, Gaps and Islands
15111513
*/----------------------------------------------------
15121514

15131515
DROP TABLE IF EXISTS #Gaps;
@@ -1552,6 +1554,18 @@ SELECT a.RowNumber,
15521554
FROM #Gaps a;
15531555
GO
15541556

1557+
--Solution 3
1558+
--LAG with IGNORE NULLS
1559+
WITH cte_Lag AS
1560+
(
1561+
SELECT *,
1562+
LAG(TestCase) IGNORE NULLS OVER (ORDER BY RowNumber) AS LagIgnoreNulls
1563+
FROM #Gaps
1564+
)
1565+
SELECT RowNumber,
1566+
(CASE WHEN TestCase IS NOT NULL THEN TestCase ELSE LagIgnoreNulls END) AS TestCase
1567+
FROM cte_Lag;
1568+
15551569
/*----------------------------------------------------
15561570
Answer to Puzzle #29
15571571
Count the Groupings
@@ -4075,6 +4089,46 @@ FROM #BatchStarts a CROSS APPLY
40754089
WHERE b.Line >= a.BatchStart AND Syntax = 'GO' AND a.Batch = b.Batch) b;
40764090
GO
40774091

4092+
/*----------------------------------------------------
4093+
Answer to Puzzle #77
4094+
Interpolation
4095+
4096+
Tags: Gaps and Islands
4097+
*/----------------------------------------------------
4098+
DROP TABLE IF EXISTS #Temp;
4099+
GO
4100+
4101+
CREATE TABLE #Temp
4102+
(
4103+
RowID INTEGER PRIMARY KEY,
4104+
myValue INTEGER NULL
4105+
);
4106+
GO
4107+
4108+
INSERT INTO #Temp (RowID, myValue) VALUES
4109+
(1,100),(2,NULL),(3,NULL),(4,200),(5,NULL),(6,300),
4110+
(7,NULL),(8,100),(9,NULL),(10,200),(11,NULL),(12,300);
4111+
GO
4112+
4113+
--LAG/LEAD with IGNORE NULLS
4114+
WITH cte_Lag AS
4115+
(
4116+
SELECT *,
4117+
LAG(myValue) IGNORE NULLS OVER (ORDER BY RowID) AS LagIgnoreNulls
4118+
FROM #Temp
4119+
),
4120+
cte_Lead AS
4121+
(
4122+
SELECT *,
4123+
LEAD(myValue) IGNORE NULLS OVER (ORDER BY RowID) AS LeadIgnoreNulls
4124+
FROM #Temp
4125+
)
4126+
SELECT a.RowID,
4127+
a.myValue,
4128+
GREATEST(a.LagIgnoreNulls, b.LeadIgnoreNulls) AS NewValue
4129+
FROM cte_Lag a INNER JOIN
4130+
cte_Lead b on a.RowID = b.RowID
4131+
ORDER BY 1;
40784132

40794133
/*----------------------------------------------------
40804134
The End

0 commit comments

Comments
 (0)