ms-sql特殊查詢及操做

將表進行分組後,查詢每組的前 2 條記錄sql

方案1:code

select * from D_Student a where(
     select count (*) from D_Student b
             where b . FStuNo= a .FStuNo and  b .FCreateDate > a .FCreateDate
)<2 order by FStuNo

提示:若是表主鍵是使用int自增,那麼下面語句也是同樣效果的同步

select * from D_Student a where(
	select count (*) from D_Student b
	where b . FStuNo = a .FStuNo and  b .FId> a .FId
)<2 order by FStuNo

方案2:io

select * from D_Student a where a.FID in(
	select top 2 FID from D_Student b where b .StuNo = a .StuNo
) order by StuNo

對比: 第一種方案效率高class

查詢某班級下的全部學生的名字,返回結果以下面格式如:張三,李四,王五效率

select  STUFF ((SELECT ','+FName
                              FROM D_Student T1
                              left outer join D_Class B
                              on T1 .FClassId = B .FID where B .FID = '02FD43159C630'    FOR XML PATH ('')), 1,1 ,'')

分頁查詢 date

方案1: 利用 row_number() over(order by 字段名),實現每頁20條記錄select

select * from (
     select * , row_number() over(order by FCreateDate ) as RowIndex
     from (
          select FID ,FName, FStuNO , FCreateDate
          from D_Student
     ) B where FID = '001'
) A
where RowIndex between 1 and 20

update 時 建立別名 作相關子查詢分頁

update D_Student   set FStuNO = (
     select FClassNo +"改"  from D_Student B
     left join D_Class C
      on B .FClassId = C .FID
     where B .FID = A .FID
) from D_Student A

一條語句實現增刪改操做,一般用於同步兩張表 ( mssql 2008)nio

merge into D_Student T --目標表
using (
                 select '001' as FId,'0000023' as FClassId,'張三' as FName,'2016-01-26' as FCreatDate,'59' as FStuNO
                                 union
                 select '002' as FId,'0000023' as FClassId,'李四' as FName,'2016-01-26' as FCreatDate,'76' as FStuNO
) S --源表
on T .FID = S . FID and T. FClassId = S. FClassId
when matched    --匹配即:當T表的FID 等於 S 的FID
then update set T.FName = S.FName , T . ClassId = S .ClassId
when not matched  --不匹配:當S表中有的 FID,但T 表中沒有
then insert values( S. FId , S. FClassId,S .FName , S .FCreatDate ,S. FStuNO)
when not matched by source and(T .FClassId= '0000023')   --不匹配:T表中有的FID,但S表中沒有
then delete ;

using:也能夠是一張表。 注意 :這邊的delete 操做不當,可能會丟失整張表

相關文章
相關標籤/搜索