日期:2014-05-18  浏览次数:20602 次

统计不连续卡号问题
数据库中有一批卡,怎样统计出每种卡的起止卡号,比如

卡种类 面值 卡号
===========================
电费卡 50 00111111
电费卡 50 00111112
电费卡 50 00111113
电费卡 50 00111114
移动卡 50 10111110
移动卡 50 10111111
移动卡 50 10111112
移动卡 50 10111113
电费卡 100 0110111112
电费卡 100 0110111113
电费卡 100 0110111114

期望得到的结果:
卡种类 面值 张数 开始卡号 结束卡号
===========================================
电费卡 50 4 00111111 00111114
电费卡 100 3 0110111113 0110111114
移动卡 50 4 10111110 10111113






------解决方案--------------------
select 卡种类 ,面值 ,count(1) 张数 ,min(卡号) 开始卡号 ,max(卡号) 结束卡号 group by 卡种类 ,面值
------解决方案--------------------
SQL code
create table tb(卡种类 varchar(10),面值 int,卡号 varchar(20))
insert into tb values('电费卡' ,50  ,'00111111')
insert into tb values('电费卡' ,50  ,'00111112')
insert into tb values('电费卡' ,50  ,'00111113')
insert into tb values('电费卡' ,50  ,'00111114')
insert into tb values('移动卡' ,50  ,'10111110')
insert into tb values('移动卡' ,50  ,'10111111')
insert into tb values('移动卡' ,50  ,'10111112')
insert into tb values('移动卡' ,50  ,'10111113')
insert into tb values('电费卡' ,100 ,'0110111112')
insert into tb values('电费卡' ,100 ,'0110111113')
insert into tb values('电费卡' ,100 ,'0110111114')

go

select 卡种类 ,面值 ,count(1) 张数 ,min(卡号) 开始卡号 ,max(卡号) 结束卡号 from tb group by 卡种类 ,面值

drop table tb

/*

卡种类        面值          张数          开始卡号                 结束卡号                 
---------- ----------- ----------- -------------------- -------------------- 
电费卡        50          4           00111111             00111114
移动卡        50          4           10111110             10111113
电费卡        100         3           0110111112           0110111114

(所影响的行数为 3 行)
*/