Recursive CTE SQL Understanding
Вставка
- Опубліковано 5 лют 2025
- with numbers as (
select 1 as n
union all
select n+1 from numbers where n=9
)
select * from numbers;
DROP TABLE if exists FamilyMembers;
-- Create FamilyMembers table
CREATE TABLE FamilyMembers (
ID INT,
Name VARCHAR(50),
ParentID INT
);
-- Insert sample data into FamilyMembers
INSERT INTO FamilyMembers (ID, Name, ParentID) VALUES
(1, 'Grandparent', NULL), -- Grandparent has no parent
(2, 'Parent1', 1), -- Parent1 is a child of Grandparent
(3, 'Parent2', 1), -- Parent2 is a child of Grandparent
(4, 'Child1', 2), -- Child1 is a child of Parent1
(5, 'Child2', 2), -- Child2 is a child of Parent1
(6, 'Child3', 3); -- Child3 is a child of Parent2
select * from FamilyMembers;
WITH FamilyTree AS (
-- Anchor member: Select the grandparent
SELECT
ID, Name, ParentID,
0 AS Level -- Level 0 for the grandparent
FROM FamilyMembers
WHERE ParentID IS NULL -- Start with the top-level family member (grandparent)
UNION ALL
-- Recursive member: Select children of the current level
SELECT
fm.ID, fm.Name, fm.ParentID,
ft.Level + 1 -- Increment the level for each generation down the tree
FROM FamilyMembers fm
INNER JOIN FamilyTree ft ON fm.ParentID = ft.ID -- Join to find direct children
)
find difference between 2 dates excluding weekends and public holidays . Basically we need to find business days between 2 given dates using SQL. Solve this problem
Thanks for your comment! I’ll be covering this problem in an upcoming video on my channel. I’ll notify you once it’s uploaded. Stay tuned!