I came across a situation today where I was given a set of date ranges (begin date to end date) and needed to de-duplicate the ranges so any overlapping dates are "collapsed" so the final result would only contain the distinct range(s) of dates. There are probably a number of solutions to this problem, but I rather liked what I came up with so I decided to post it here for posterity. Code first, explanation after:
-- Declare a table variable for test data
DECLARE @Data TABLE
(
BeginDate DATETIME,
EndDate DATETIME
);
-- Fill the test data
INSERT INTO @Data
SELECT '2016-01-01', '2016-01-05'
UNION ALL SELECT '2016-01-03', '2016-01-10'
UNION ALL SELECT '2016-01-12', '2016-01-15'
UNION ALL SELECT '2016-01-14', '2016-01-18'
UNION ALL SELECT '2016-01-16', '2016-01-25'
UNION ALL SELECT '2016-01-16', '2016-01-20'
UNION ALL SELECT '2016-01-16', '2016-01-20'
UNION ALL SELECT '2016-02-01', '2016-03-13'
UNION ALL SELECT '2016-05-01', '2016-05-30'
UNION ALL SELECT '2016-05-28', '2016-06-10';
WITH S AS (
SELECT BeginDate, MAX(EndDate) AS EndDate -- Select the starting ranges
FROM @Data D
WHERE NOT EXISTS(SELECT * FROM @Data WHERE BeginDate < D.BeginDate AND EndDate >= D.BeginDate)
GROUP BY BeginDate
UNION ALL
SELECT S.BeginDate, D.EndDate -- recursively expand the ranges
FROM S
INNER JOIN @Data D ON D.BeginDate BETWEEN S.BeginDate AND S.EndDate
AND D.EndDate > S.EndDate
)
SELECT BeginDate, MAX(EndDate)
FROM S
GROUP BY BeginDate;
In this example, I used a common table expression (CTE) for my test data. The work is done by the "S" CTE. It starts by selecting any date range that doesn't have another date range that overlaps its begin date, grouping by that begin date, to select the max end date (to eliminate any ranges that start on the same day). It then recursively joins back to the original data, bringing in any date range that overlaps and has an end date further out. In the final output, you select the BeginDate and MAX(EndDate) to get your distinct list of date ranges.
If you have additional columns you need to group by, you'll need to add them in. For example:
-- Declare a table variable for test data
DECLARE @Data TABLE
(
ID INT,
BeginDate DATETIME,
EndDate DATETIME
);
-- Fill the test data
INSERT INTO @Data
SELECT 1, '2016-01-01', '2016-01-05'
UNION ALL SELECT 1, '2016-01-03', '2016-01-10'
UNION ALL SELECT 1, '2016-01-12', '2016-01-15'
UNION ALL SELECT 1, '2016-01-14', '2016-01-18'
UNION ALL SELECT 1, '2016-01-16', '2016-01-25'
UNION ALL SELECT 2, '2016-01-16', '2016-01-20'
UNION ALL SELECT 2, '2016-01-16', '2016-01-20'
UNION ALL SELECT 2, '2016-02-01', '2016-03-13'
UNION ALL SELECT 2, '2016-05-01', '2016-05-30'
UNION ALL SELECT 2, '2016-05-28', '2016-06-10';
WITH S AS (
SELECT ID, BeginDate, MAX(EndDate) AS EndDate -- Select the starting ranges
FROM @Data D
WHERE NOT EXISTS(SELECT * FROM @Data WHERE ID = D.ID AND BeginDate < D.BeginDate AND EndDate >= D.BeginDate)
GROUP BY ID, BeginDate
UNION ALL
SELECT S.ID, S.BeginDate, D.EndDate -- recursively expand the ranges
FROM S
INNER JOIN @Data D ON S.ID = D.ID
AND D.BeginDate BETWEEN S.BeginDate AND S.EndDate
AND D.EndDate > S.EndDate
)
SELECT ID, BeginDate, MAX(EndDate)
FROM S
GROUP BY ID, BeginDate;
Executive Standing Desks
ReplyDeleteFor those who take leadership seriously, the Fezibo Executive Standing Desk offers a premium workspace that matches your ambition. This desk features a spacious surface area designed for dual monitors, files, and all your essentials, while its dual-motor lift system ensures a smooth and powerful transition between sitting and standing. The modern aesthetic blends wood textures or sleek finishes with industrial-strength durability. With programmable memory presets, anti-collision protection, and a solid steel frame, Fezibo delivers more than just ergonomics—it creates an executive experience that promotes health and focus without compromising on elegance. https://www.fezibo.com/collections/executive-standing-desks
Standing Corner Desk
ReplyDeleteNeed more room without sacrificing comfort? The Fezibo Standing Corner Desk is the perfect answer. Its L-shaped design fits naturally into corners or open-plan offices, maximizing usable space while maintaining an ergonomic layout. Whether you're managing spreadsheets, designing, or taking video calls, this desk keeps everything within reach. The smooth electric lift system allows you to switch postures easily, reducing fatigue and enhancing productivity. Crafted for stability, the Fezibo corner desk is ideal for multitaskers who want organization, comfort, and a polished look in one flexible design. https://www.fezibo.com/collections/corner-standing-desk
Standing Desk White
ReplyDeleteRefresh your office with the minimalist elegance of the Fezibo Standing Desk White. Its clean lines and bright surface evoke clarity and calm—perfect for creative professionals, remote workers, or anyone who thrives in a distraction-free environment. The whisper-quiet electric lift lets you change heights effortlessly, and the preset memory buttons make it easy to return to your perfect position. From form to function, this desk delivers a user-friendly experience with a modern edge. Fezibo’s white desk isn’t just beautiful—it’s designed to keep your body and mind aligned throughout the day. https://www.fezibo.com/collections/white-standing-desk
Standing Desk Wood
ReplyDeleteClassic and comforting, the Fezibo Standing Desk Wood is where traditional style meets cutting-edge ergonomics. The rich wood surface pairs seamlessly with a sturdy steel frame, offering timeless appeal alongside advanced functionality. The quiet lift system promotes active work habits and reduces tension from long sitting hours. Whether you're crafting documents or brainstorming new ideas, this desk encourages healthier movement while complementing your office with natural tones. Fezibo’s attention to design and reliability makes this wooden standing desk a long-term investment in both comfort and aesthetics. https://www.fezibo.com/collections/wooden-standing-desk
Hand Crank Standing Desk
ReplyDeleteNo power? No problem. The Fezibo Hand Crank Standing Desk is the perfect manual alternative for those who value independence, simplicity, or energy-saving solutions. Its smooth crank system gives you full control over height adjustments, allowing precise transitions with minimal effort. The solid metal frame and customizable width make it adaptable for different spaces—from classrooms to shared offices. It's also ideal for people who prefer non-electric solutions or want to avoid complicated settings. Fezibo ensures that even a hand-crank desk comes packed with ergonomic support and everyday durability. https://www.fezibo.com/products/fezibo-manual-crank-standing-desk
Glass Top Standing Desk
ReplyDeleteThe Fezibo Glass Top Standing Desk adds a sophisticated, high-tech edge to your workspace. With its glossy, scratch-resistant tempered glass surface, this desk is as elegant as it is practical. Beneath the sleek surface lies a responsive motorized lift system that adjusts to your perfect working height in seconds. Fezibo includes intuitive features like memory presets, anti-collision technology, and a weight-bearing steel base. Whether you’re aiming for a minimalist aesthetic or a cutting-edge home office, this glass-top standing desk gives you the confidence to work in style and comfort. https://www.fezibo.com/products/fezibo-glass-top-standing-desk
Bamboo Standing Desk
ReplyDeleteCelebrate sustainable living with the Fezibo Bamboo Standing Desk, where natural beauty meets functional design. Bamboo isn’t just an eco-conscious material—it’s lightweight, incredibly strong, and adds a warm, organic touch to any environment. The electric lift mechanism operates smoothly, helping you stay mobile and avoid stiffness during long hours. With pre-drilled grommets and anti-collision safety, Fezibo offers the perfect blend of green design and smart engineering. This desk is ideal for modern professionals who want to work better while leaving a smaller footprint on the planet. https://www.fezibo.com/products/fezibo-bamboo-top-standing-desk
Standing Desk with Keyboard Tray
ReplyDeleteIf typing ergonomics matter to you, the Fezibo Standing Desk with Keyboard Tray should be your go-to. Designed with a retractable keyboard platform, this desk allows you to type at the correct angle, preventing wrist strain and promoting neutral hand alignment. The tray slides out smoothly and supports a full keyboard-and-mouse setup. Paired with electric lift capability, this desk helps you create a healthier, more productive workflow. From coders to writers, anyone who spends long hours at the keyboard will appreciate Fezibo’s thoughtful, comfort-focused design. https://www.fezibo.com/products/fezibo-standing-desk-with-keyboard-tray
Cheapest Standing Desk
ReplyDeleteWorking on a tight budget? The Fezibo Cheapest Standing Desk offers exceptional value without compromising quality. Featuring either a manual or electric lift system, this desk allows you to enjoy the health benefits of standing while working, at a fraction of the typical cost. It’s sturdy enough for your daily gear and offers a clean, modern appearance that suits dorm rooms, small apartments, or startup spaces. Fezibo proves that affordability doesn’t mean cutting corners—it means smart design, durable materials, and accessible ergonomics for everyone. https://www.fezibo.com/deals
Ergonomic Office Chair
ReplyDeletePair your Fezibo desk with the Fezibo Ergonomic Office Chair, built to support you through long hours of work or study. This chair features adjustable lumbar support, height, armrests, and tilt to fit your body perfectly. The mesh back promotes airflow while the padded seat keeps you comfortable, even during marathon work sessions. Whether used on its own or with a standing desk, this chair encourages better posture and reduces fatigue. Fezibo brings the same attention to ergonomic detail to its chairs as it does to its desks—because your whole body deserves support. https://www.fezibo.com/collections/ergonomic-chairs