Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Getting Consecutive Day Count Grouped By

$
0
0

I am trying to get the consecutive count of days (grouped by homeroom & building) from a table without having to use a cursor. The count should only include days <= @MaxDate in consecutive order without any gaps.

DECLARE @MaxDate AS DATE
SET @MaxDate = '11/10/2013'

CREATE TABLE #Homeroom
(
	[hr_date] [date] NULL,
	[homeroom] [nvarchar](5) NULL,
	[building] [nvarchar](4) NULL
)


INSERT INTO #Homeroom (hr_date, homeroom, building) VALUES ('11/1/2013', '100', '105')
INSERT INTO #Homeroom (hr_date, homeroom, building) VALUES ('11/3/2013', '100', '105')
INSERT INTO #Homeroom (hr_date, homeroom, building) VALUES ('11/5/2013', '100', '105')
INSERT INTO #Homeroom (hr_date, homeroom, building) VALUES ('11/6/2013', '100', '105')
INSERT INTO #Homeroom (hr_date, homeroom, building) VALUES ('11/7/2013', '100', '105')
INSERT INTO #Homeroom (hr_date, homeroom, building) VALUES ('11/8/2013', '100', '105')
INSERT INTO #Homeroom (hr_date, homeroom, building) VALUES ('11/9/2013', '100', '105')
INSERT INTO #Homeroom (hr_date, homeroom, building) VALUES ('11/10/2013', '100', '105')

INSERT INTO #Homeroom (hr_date, homeroom, building) VALUES ('11/5/2012', '217', '105')
INSERT INTO #Homeroom (hr_date, homeroom, building) VALUES ('11/7/2012', '217', '105')
INSERT INTO #Homeroom (hr_date, homeroom, building) VALUES ('11/8/2012', '217', '105')
INSERT INTO #Homeroom (hr_date, homeroom, building) VALUES ('11/10/2012', '217', '105')

--Query should return noting because the latest date < @MaxDate
INSERT INTO #Homeroom (hr_date, homeroom, building) VALUES ('11/5/2012', '100', '106')
INSERT INTO #Homeroom (hr_date, homeroom, building) VALUES ('11/7/2012', '100', '106')
INSERT INTO #Homeroom (hr_date, homeroom, building) VALUES ('11/8/2012', '100', '106')
INSERT INTO #Homeroom (hr_date, homeroom, building) VALUES ('11/9/2012', '100', '106')

Based on the sample data I am hoping to get a result set like this

homeroom	building	consecutive_count
100			105			6
217			105			1

Any ideas?



Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>