日期:2014-05-17  浏览次数:20381 次

求SQL语句计算单据使用情况

如上图,表一是单据类型,表二是使用情况。
单据使用情况不一定连续
求计算报表单据余额情况统计:
单据类型   剩余单据起始号    剩余单据结束号    剩余单据份数
打印发票     583881          583990          110
... 


求计算语句
------最佳解决方案--------------------
create table 单据类型表(单据类型 varchar(20),单据起始号 int,单据结束号 int)
insert into 单据类型表
select '打印发票',100,800
union all
select '定额发票',1000,6000
union all 
select '手工发票',30,60

create table 使用情况表(单据类型 varchar(20),单据使用起始号 int,单据使用结束号 int)
insert into 使用情况表
select '打印发票',100,200
union all
select  '打印发票',400,500
union all
select  '定额发票',2000,4000

----测试
with TB as (
select 单据类型,单据使用起始号,单据使用结束号,ROW_NUMBER() over(partition by 单据类型 order by 单据使用起始号) as rowid
from 使用情况表)

select 单据类型,case when flag=1 or flag=3 then 剩余单据起始号+1 else 剩余单据起始号 end 剩余单据起始号,
case when flag=1 or flag=2 then 剩余单据结束号-1 else 剩余单据结束号 end 剩余单据结束号,
(case when flag=1 or flag=2 then 剩余单据结束号-1 else 剩余单据结束号 end)-(case when flag=1 or flag=3 then 剩余单据起始号+1 else 剩余单据起始号 end) as 剩余单据份数
from (
select a.单据类型,a.单据使用结束号 剩余单据起始号,b.单据使用起始号 剩余单据结束号,1 as flag
from TB as a inner join TB as b on a.rowid=b.rowid-1 and a.单据类型=b.单据类型
union all
select 单据类型,单据起始号 as 起始号,isnull((select MIN(单据使用起始号) from 使用情况表 where 单据类型=a.单据类型),a.单据结束号) 结束号,
case when (select MIN(单据使用起始号) from 使用情况表 where 单据类型=a.单据类型) IS null then 4 else 2 end as flag
from 单据类型表 as a 
union all
select 单据类型,(select max(单据使用结束号) from 使用情况表 where 单据类型=a.单据类型),单据结束号,3 as flag
from 单据类型表 as a 
) as X
where 剩余单据结束号<>剩余单据起始号
order by 单据类型,剩余单据起始号
------其他解决方案--------------------
如果是SQL2000该怎么写? 不支持ROW_NUMBER()
 
------其他解决方案--------------------
引用:
create table 单据类型表(单据类型 varchar(20),单据起始号 int,单据结束号 int)
insert into 单据类型表
select '打印发票',100,800
union all
select '定额发票',1000,6000
union all 
select '手工发票',30,60

create table 使用情况表(单据类型 varch……

按照此语句的结果不全对:

单据份数负数的记录应该去掉的
------其他解决方案--------------------
谁来帮我再看看!!