Sqlserver Max with Over
if you have alteast one entry in your table than this will be fastest
Declare @tblMinMaxExample table
(
pk integer not null identity(1,1) primary key,
dataYearMonth integer,
dataYear integer,
dataMonth integer,
recordedValue float,
attributeA varchar(1),
attributeB varchar(1)
)
insert into @tblMinMaxExample values (201401, 2014, 1, 200.0, 'A', 'a')
insert into @tblMinMaxExample
select '201412', '2014', max(dataMonth) over(order by pk)
, 100.0, 'L', 'l' from @tblMinMaxExample
else use this
Declare @tblMinMaxExample table
(
pk integer not null identity(1,1) primary key,
dataYearMonth integer,
dataYear integer,
dataMonth integer,
recordedValue float,
attributeA varchar(1),
attributeB varchar(1)
)
--insert into @tblMinMaxExample values (201401, 2014, 1, 200.0, 'A', 'a')
--insert into @tblMinMaxExample values (201402, 2014, 2, 400.0, 'B', 'b')
--insert into @tblMinMaxExample values (201403, 2014, 3, 600.0, 'C', 'c')
--insert into @tblMinMaxExample values (201404, 2014, 4, 800.0, 'D', 'd')
--insert into @tblMinMaxExample values (201405, 2014, 5, 1000.0, 'E', 'e')
--insert into @tblMinMaxExample values (201406, 2014, 6, 1200.0, 'F', 'f')
--insert into @tblMinMaxExample values (201407, 2014, 7, 1100.0, 'G', 'g')
--insert into @tblMinMaxExample values (201408, 2014, 8, 900.0, 'H', 'h')
--insert into @tblMinMaxExample values (201409, 2014, 9, 700.0, 'I', 'i')
--insert into @tblMinMaxExample values (201410, 2014, 10, 500.0, 'J', 'j')
--insert into @tblMinMaxExample values (201411, 2014, 11, 300.0, 'K', 'k')
--insert into @tblMinMaxExample values (201412, 2014, 12, 100.0, 'L', 'l')
insert into @tblMinMaxExample
values ('201412', '2014', isnull( (select max(dataMonth) over(order by pk) from @tblMinMaxExample ), 1)
, 100.0, 'L', 'l' )
select * from @tblMinMaxExample
Comments
Post a Comment