Quantcast
Channel: SQLServerCentral » SQL Server 2012 » SQL Server 2012 - T-SQL » Latest topics
Viewing all articles
Browse latest Browse all 4901

Find First and Last Period without holes

$
0
0
OK, first post and Subject I can not phrase any better.1. I have a table where all records have a field for period.2. For each record I want to know what the first and last periods are in which the period of the current record falls, without missing periods.Assume Table t1:KEY Period Data (Key is three fields + Period)A 5 dataA 6 dataA 8 dataI want a query that yields:KEY Period Data FirstPeriod LastPeriodA 5 data 5 6A 6 data 5 6A 8 data 8 8I have got it but it must be extremely inefficient. I do (for FP (FirstPeriod) only, LP is similar):UPDATE t1SET FP = ( SELECT MAX(Period) FROM ( SELECT t2.KEY, t2.Period FROM vAT t2 LEFT JOIN vAT t3 ON t2.KEY = t3.KEY AND t2.Per = t3.Per+1 WHERE t3.Per IS NULL AND t1.KEY = t2.KEY AND t1.Per >= t2.Per ) as tfp )FROM vAT t1It does what I need but this can't be right/efficient, can it?Kind rgds,Umf

Viewing all articles
Browse latest Browse all 4901

Trending Articles