国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > 綜合 > 正文

動態分組查詢

2024-07-21 02:07:05
字體:
來源:轉載
供稿:網友
  • 本文來源于網頁設計愛好者web開發社區http://www.html.org.cn收集整理,歡迎訪問。

  • 原帖地址:
    http://community.csdn.net/expert/topic/3428/3428792.xml?temp=.6476251

    --示例數據
    create table 表(id int,num int)
    insert 表 select 1,2
    union all select 2,3
    union all select 3,2
    union all select 4,2
    union all select 5,12
    union all select 6,2
    union all select 7,1
    union all select 8,5
    union all select 9,1
    go

    /*--問題說明:

    輸入分組參數,比如輸入 "3,6" ,實現按 id<=3,3<id<=6,id>6 分組查詢
    輸入分組參數,比如輸入 "2,5,8" ,實現按 id<=2,2<id<=5,5<id<=8,id>8 分組查詢
    --*/

    --查詢的存儲過程
    create proc p_qry
    @numlist varchar(1000)
    as
    set nocount on
    declare @t table(id int identity,組 varchar(10),a int,b int)
    declare @i int,@pnum varchar(10)
    select @i=charindex(',',@numlist+',')
     ,@pnum=left(@numlist,@i-1)
     ,@numlist=stuff(@numlist,1,@i,'')
     ,@i=charindex(',',@numlist)
    insert @t select 'id<='[email protected],null,@pnum
    while @i>0
    begin
     insert @t select @pnum+'<id<='+left(@numlist,@i-1),@pnum,left(@numlist,@i-1)
     select @pnum=left(@numlist,@i-1)
      ,@numlist=stuff(@numlist,1,@i,'')
      ,@i=charindex(',',@numlist)
    end
    insert @t select 'id>'[email protected],@numlist,null

    select b.組,num=sum(a.num)
    from 表 a,@t b
    where case
     when b.a is null then case when a.id<=b.b then 1 else 0 end
     when b.b is null then case when a.id>b.a then 1 else 0 end
     else case when a.id>b.a and a.id<=b.b then 1 else 0 end
     end=1
    group by b.組
    order by min(b.id)
    go

    --調用存儲過程進行查詢
    exec p_qry '2,5,8'
    go

    --刪除測試
    drop table 表
    drop proc p_qry

    /*--測試結果

    組          num        
    ---------- -----------
    id<=2      5
    2<id<=5    16
    id>8       1
    --*/
    發表評論 共有條評論
    用戶名: 密碼:
    驗證碼: 匿名發表
    主站蜘蛛池模板: 富顺县| 伊春市| 佳木斯市| 克山县| 肇庆市| 河西区| 绵竹市| 芒康县| 舒城县| 汶上县| 万荣县| 霍邱县| 花莲市| 凤翔县| 揭东县| 长岭县| 江口县| 九龙城区| 乌兰浩特市| 吴桥县| 苏尼特右旗| 樟树市| 普兰店市| 新乡市| 定日县| 瑞金市| 包头市| 自治县| 新野县| 楚雄市| 河北区| 稷山县| 来凤县| 浏阳市| 桦甸市| 思茅市| 河津市| 大悟县| 伊吾县| 沂水县| 潢川县|