需要提取来自不同县的记录的可变计数

时间:2019-02-13 20:53:17

标签: sql-server

我有一个名为采购清单的表,该表具有县FIPS和最常用姓氏的姓氏计数。

Fips    mdLASTNAME  MOST_FREQUENT rn
37109   SMITH                           953 1
37109   JOHNSON                         496 2
37109   WILLIAMS                        376 3
37109   BROWN                           354 4
37109   WILSON                          315 8
37119   BURNS                           535 162
37119   BRADLEY                         534 163
37119   WATKINS                         531 164
37119   STEELE                          529 165
37119   BERRY                           528 166

我需要从FIPS 37109中提取953个姓氏为Smith的记录,并且 496条来自FIPS 37109的姓氏JOHNSON的记录 528条来自FIPS 37119的姓氏Berry的记录,因此没有 从表中称为客户。

declare lineCursor12 cursor
fast_forward
for 
select DISTINCT FIPS from #temp5 

declare @Fips varchar(5)

open lineCursor12
fetch next from lineCursor12 into @Fips 
       while @@FETCH_STATUS=0
       begin                  
                     insert into dbo.test
                     Select * from dbo.Customer
                     where  mdFips=@Fips ORDER BY MOST_FREQUENT desc)




                     fetch next from lineCursor12 into @Fips
       end

close lineCursor12
deallocate lineCursor12

1 个答案:

答案 0 :(得分:0)

声明lineCursor12光标 快进 对于 从[Workspace]中选择FIPS,[MOST_FREQUENT],[LASTNAME]。[dric]。[EriclastName2]其中FIPS在('37119','37109')

声明@Fips varchar(5) 声明@MOST_FREQUENT int 声明@LASTNAME varchar(50)

打开lineCursor12 接下来从lineCursor12获取@ Fips,@ MOST_FREQUENT,@ LASTNAME        而@@ FETCH_STATUS = 0        开始

                 set rowcount @MOST_FREQUENT
                 insert into dbo.finallastname


                 Select [aFIRSTNAME],[aMIDDLEINITIAL],[aLASTNAME],[NameCat],[aFips] from dbo.consumer
                 WITH(INDEX(IX_aLastName_aFips))
                 where aFips=@Fips and [aLASTNAME]= @LASTNAME 
                 Set rowcount 0



                 fetch next from lineCursor12 into @Fips,@MOST_FREQUENT,@LASTNAME
   end

关闭lineCursor12 取消分配lineCursor12