MSSQL求連續ID內數量合計 常見解決方案

2021-09-30 08:15:52 字數 2427 閱讀 2042

--> title  : mssql求連續id內數量合計-常見解決方案

--> author : wufeng4552

--> date   : 2009-12-04

if object_id('tb') is not null drop table tb

gocreate table tb(id varchar(10),num decimal(10,2)) 

insert tb

select '001',200.00 union all

select '002',200.00 union all

select '003',300.00 union all

select '007',500.00 union all

select '008',800.00 union all

select '009',200.00 union all

select '012',100.00 union all

select '013',100.00 union all

select '014',200.00 union all

select '017',100.00 union all

select '018',400.00 union all

select '019',300.00 

-->方法 1 臨時表

if object_id('tempdb..#t1')is not null 

drop table #t1

if object_id('tempdb..#t2')is not null 

drop table #t2

go--取出起號

select cnt=identity(int,1,1),* into #t1 from tb t where not exists(select 1 from tb where id=t.id-1)order by t.id

--取出止號

select cnt=identity(int,1,1),* into #t2 from tb t where not exists(select 1 from tb where id=t.id+1)order by t.id

select n.[start]+'-'+n.[end]起止號,sum(num)合計

from tb m,

(select a.id [start],b.id [end] from #t1 a,#t2 b where a.cnt=b.cnt) n

where m.id between n.[start] and n.[end]

group by n.[start]+'-'+n.[end]

起止號                  合計

001-003               700.00

007-009               1500.00

012-014               400.00

017-019               800.00

(4 個資料列受到影響)

--方法 2

select case when min(t.id)!=max(t.id) then min(t.id)+'-'+max(t.id)else min(t.id)end 起止號, 

sum(num)合計

from(

select id,

cnt=cast(id as int)-(select count(*)from tb n where m.id>n.id),

numfrom tb m

)t group by cnt

起止號                  合計

001-003               700.00

007-009               1500.00

012-014               400.00

017-019               800.00

(4 個資料列受到影響)

--方法3

select case when min(t.id)!=max(t.id) then min(t.id)+'-'+max(t.id)else min(t.id)end 起止號, 

sum(num)合計

from(

select id,cnt=id-row_number()over(order by getdate()),num from tb

)t group by cnt

起止號                  合計

001-003               700.00

007-009               1500.00

012-014               400.00

017-019               800.00

(4 個資料列受到影響)

求規定範圍內的完美數

輸入 檔名稱 sum123.cpp 作 者 林海雲 完成日期 2014年12月24日 版 本 號 v2.0 問題描述 求規定範圍內滿足條件的完美數。6的所有真約數是1 2 3,而且6 1 2 3。像這樣,乙個數所有真約數的和正好等於這個數,通常把這個數叫做完美數 程式輸入 m x n且輸入0 0結束...

華為OJ 求最大連續bit數

求最大連續bit 數功能 求乙個byte 數字對應的二進位制數字中 1的最大連續數,例如 3的二進位制為 00000011 最大連續2個 1輸入 乙個byte 型的數字 輸出 無返回 對應的二進位制數字中 1的最大連續數 輸入描述 輸入乙個byte 數字輸出描述 輸出轉成二進位制之後連續1 的個數輸...

華為OJ 求最大連續bit數

將數字和1進行按位與運算,然後將數字向右移一位,直到數字變為0為止。include include includeusing namespace std int main sort count.begin count.end cout count count.size 1 endl return 0...