问题
- /*
- 问题:***统计不连续卡号问题****
- 数据库中有一批卡,怎样统计出每种卡的起止卡号,比如
- 卡种类 面值 卡号
- ===========================
- 电费卡 50 00111111
- 电费卡 50 00111112
- 电费卡 50 00111113
- 电费卡 50 00111114
- 电费卡 50 00111119
- 电费卡 50 00111120
- 电费卡 50 00111121
- 电费卡 50 00111122
- 移动卡 50 10111110
- 移动卡 50 10111111
- 移动卡 50 10111112
- 移动卡 50 10111113
- 电费卡 100 0110111112
- 电费卡 100 0110111113
- 电费卡 100 0110111114
- 期望得到的结果:
- 卡种类 面值 张数 开始卡号 结束卡号
- ===========================================
- 电费卡 50 4 00111111 00111114
- 电费卡 50 4 00111119 00111122
- 电费卡 100 3 0110111113 0110111114
- 移动卡 50 4 10111110 10111113
- */
SQL
- --sql
- create table #card (cardtype varchar(20),cardvalue int,cardno varchar(20))
- insert into #card
- select '电费卡','50','00111111'
- union all select '电费卡','50','00111112'
- union all select '电费卡','50','00111113'
- union all select '电费卡','50','00111114'
- union all select '电费卡','50','00111119'
- union all select '电费卡','50','00111120'
- union all select '电费卡','50','00111121'
- union all select '电费卡','50','00111122'
- union all select '移动卡','50','10111110'
- union all select '移动卡','50','10111111'
- union all select '移动卡','50','10111112'
- union all select '移动卡','50','10111113'
- union all select '电费卡','100','0110111112'
- union all select '电费卡','100','0110111113'
- union all select '电费卡','100','0110111114'
- select ROW_NUMBER() over (order by t1.cardno),t1.* from #card t1
- select convert(bigint,t.cardno)-no as type,t.* from (
- select ROW_NUMBER() over (order by t1.cardno) as no,t1.* from #card t1 ) t
- select type,cardtype,cardvalue,COUNT(*),MIN(cardno),MAX(cardno)
- from (
- select convert(bigint,t.cardno)-no as type,t.* from (
- select ROW_NUMBER() over (order by t1.cardno) as no,t1.* from #card t1 ) t
- ) tt
- group by type,cardtype,cardvalue
- --最终sql
- select cardtype,cardvalue,cnt,mincardno,maxcardno from (
- select type,cardtype,cardvalue,COUNT(*) as cnt,MIN(cardno) as mincardno,MAX(cardno) as maxcardno
- from (
- select convert(bigint,t.cardno)-no as type,t.* from (
- select ROW_NUMBER() over (order by t1.cardno) as no,t1.* from #card t1 ) t
- ) tt
- group by type,cardtype,cardvalue
- ) ttt
结果
- /* 结果
- cardtype cardvalue cnt mincardno maxcardno
- -------------------- ----------- ----------- -------------------- --------------------
- 电费卡 50 4 00111111 00111114
- 电费卡 50 4 00111119 00111122
- 移动卡 50 4 10111110 10111113
- 电费卡 100 3 0110111112 0110111114
- (4 行受影响)
- */
清理sql
- drop table #card