当前位置: 代码迷 >> Sql Server >> [求购SQL 语句一条]解决方案
  详细解决方案

[求购SQL 语句一条]解决方案

热度:24   发布时间:2016-04-27 12:57:51.0
[求购SQL 语句一条]
SQL code
create table #tmp(  Id int,  BatchNo varchar(10),  Num int )insert into #tmp select 1, 'B0001',10insert into #tmp select 2, 'B0002',10insert into #tmp select 5, 'B0003',30insert into #tmp select 9, 'B0004',40insert into #tmp select 10,'B0005',20*********--问题,查询出满足出库数量的批次,比我如出库数量是50, 那么就返回批次Id    1,2,5--如果出库数量是30,返回批次Id   1,2,5


------解决方案--------------------
都是1,2,5?
------解决方案--------------------
你50是1,2,5
30也是1,2,5
求解释啊
------解决方案--------------------
SQL code
create table #tmp(  Id int,  BatchNo varchar(10),  Num int )insert into #tmp select 1, 'B0001',10insert into #tmp select 2, 'B0002',10insert into #tmp select 5, 'B0003',30insert into #tmp select 9, 'B0004',40insert into #tmp select 10,'B0005',20--30select    stuff(( select ',' + CAST(ID AS VARCHAR(10))                 from #tmp AS B WHERE B.Id NOT IN (SELECT ID                                                  FROM #tmp AS A                                                  WHERE 30 <= (SELECT SUM(Num) FROM #tmp  AS B WHERE A.Id > B.Id)) for xml path('')),1,1,'') as IDs--结果IDs1,2,5--50select    stuff(( select ',' + CAST(ID AS VARCHAR(10))                 from #tmp AS B WHERE B.Id NOT IN (SELECT ID                                                  FROM #tmp AS A                                                  WHERE 50 <= (SELECT SUM(Num) FROM #tmp  AS B WHERE A.Id > B.Id)) for xml path('')),1,1,'') as IDs--结果IDs1,2,5
------解决方案--------------------
SQL code
create table t1(    id int,    batchno varchar(10),    num int)insert into t1 select 1, 'B0001',10insert into t1 select 2, 'B0002',10insert into t1 select 5, 'B0003',30insert into t1 select 9, 'B0004',40insert into t1 select 10,'B0005',20select * from t1declare @num intset @num=30;with aaa as(select ROW_NUMBER() over(order by id) as rowindex,a.*,(select SUM(num)[email protected] from t1 where t1.id<=a.id) as num1 from t1 as a)select id from aaa where rowindex<=(select top 1 rowindex from aaa where num1>=0 order by num1)-------------------------------id125
------解决方案--------------------
SQL code
with tb as(select *,rank()over(order by id) as row,num1=(select (isnull(sum(num),0)) as num from #tmp where id<a.id),num2=(select (sum(num)) as num from #tmp where id<=a.id) from #tmp a)select id=stuff((select ','+cast(id as varchar(10)) from tb where row<=a.row for xml path('')),1,1,'') from tb a where num1<30 and num2>=30
------解决方案--------------------
楼上正解
  相关解决方案