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

求SQL算法
TABLE:
create table u_inout_break(
  execdate datetime not null,
  billcode varchar(10) not null,
  busno varchar(10) not null,
  wareid varchar(13) not null,
  billno varchar(30) not null,
  flag tinyint not null, --0:缺货;1:到货
  storeqty numeric(16,6) not null, --业务发生后的库存余额
  stamp timestamp not null
  primary key(execdate,billcode,busno,wareid,billno,flag)
  )

表内容:(可直接运行以便调试)
 INSERT u_inout_break(execdate,billcode,busno,wareid,billno,flag,inoutqty,endqty) values("12 3 2007 11:49AM","WHL","51802","1030141","",0,-100.000000,0.000000)
 INSERT u_inout_break(execdate,billcode,busno,wareid,billno,flag,inoutqty,endqty) values("12 5 2007 11:45AM","WHL","51802","1030468","",0,-450.000000,0.000000)
 INSERT u_inout_break(execdate,billcode,busno,wareid,billno,flag,inoutqty,endqty) values("12 5 2007 11:46AM","acc","51802","1030468","",1,100.000000,100.000000)
 INSERT u_inout_break(execdate,billcode,busno,wareid,billno,flag,inoutqty,endqty) values("12 6 2007 11:51AM","acc","51802","1030141","",1,230.000000,230.000000)
 INSERT u_inout_break(execdate,billcode,busno,wareid,billno,flag,inoutqty,endqty) values("12 6 2007 12:01PM","WHL","51802","1030468","",0,-200.000000,0.000000)
 INSERT u_inout_break(execdate,billcode,busno,wareid,billno,flag,inoutqty,endqty) values("12 9 2007 2:09PM","acc","51802","1030468","",1,12.000000,12.000000)
 INSERT u_inout_break(execdate,billcode,busno,wareid,billno,flag,inoutqty,endqty) values("12 12 2007 2:12PM","WHL","51802","1030468","",0,-12.000000,0.000000)
 INSERT u_inout_break(execdate,billcode,busno,wareid,billno,flag,inoutqty,endqty) values("12 13 2007 2:25PM","acc","51802","1030468","",1,23.000000,23.000000)
 INSERT u_inout_break(execdate,billcode,busno,wareid,billno,flag,inoutqty,endqty) values("12 13 2007 2:26PM","WHL","51802","1030468","",0,-23.000000,0.000000)
 INSERT u_inout_break(execdate,billcode,busno,wareid,billno,flag,inoutqty,endqty) values("12 14 2007 2:26PM","acc","51802","1030468","",1,34.000000,34.000000)


表内容如下:
时间 业务单位 商品编码 标志
2007-12-03 11:49:45.873 51802 1030141 0
2007-12-06 11:51:42.610 51802 1030141 1
2007-12-05 11:45:30.420 51802 1030468 0
2007-12-05 11:46:36.560 51802 1030468 1
2007-12-06 12:01:18.530 51802 1030468 0
2007-12-09 14:09:30.840 51802 1030468 1
2007-12-12 14:12:59.967 51802 1030468 0
2007-12-13 14:25:35.577 51802 1030468 1
2007-12-13 14:26:21.480 51802 1030468 0
2007-12-14 14:26:47.840 51802 1030468 1
 


问题:
“标志”字段为0的说明是某商品断货时间,“标志”为1的说明是某商品的到货时间,某商品在一段时间内会有多次的断货,我想计算某业务单位,某商品的断货天数。
如:商品1030468的总计断货天数为:
select datediff(dd,'2007-12-05','2007-12-05') + 
  datediff(dd,'2007-12-06','2007-12-09') + 
  datediff(dd,'2007-12-12','2007-12-13') + 
  datediff(dd,'2007-12-13','2007-12-14')

提示:
如果能得到下面结果集,就很容易计算出来了。
51802 1030468 '2007-12-05' '2007-12-05'
51802 1030468 '2007-12-06' '2007-12-09'
51802 1030468