CUT表结构如下
CID CTYPE CQTY QTY SQTY SNO
F21 0010 8 null 10 T1099
F22 0010 3 null 10 T1099
F23 0010 2 null 10 T1099
F31 0010 6 null 6 T8899
F32 0010 2 null 6 T8899
我想用SQTY(总量)-CQTy(需求量),在把实际得到的值给QTY,大体格式如下:
CID CTYPE CQTY QTY SQTY SNO
F21 0010 8 8 10 T1099
F22 0010 3 2 10 T1099
F23 0010 2 0 10 T1099
F31 0010 6 6 6 T8899
F32 0010 2 0 6 T8899
如何做?谢谢,我之前尝试变量但是不行,而且还慢,求解,谢谢
------解决思路----------------------
我觉得这个才是合理的结果
----------------------------------------------------------------
-- Author :DBA_HuangZJ(發糞塗牆)
-- Date :2014-09-29 14:53:43
-- Version:
-- Microsoft SQL Server 2012 - 11.0.5058.0 (X64)
-- May 14 2014 18:34:29
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据:[CUT]
if object_id('[CUT]') is not null drop table [CUT]
go
create table [CUT]([CID] varchar(3),[CTYPE] varchar(4),[CQTY] int,[QTY] sql_variant,[SQTY] int,[SNO] varchar(5))
insert [CUT]
select 'F21','0010',8,null,10,'T1099' union all
select 'F22','0010',3,null,10,'T1099' union all
select 'F23','0010',2,null,10,'T1099' union all
select 'F31','0010',6,null,6,'T8899' union all
select 'F32','0010',2,null,6,'T8899'
--------------开始查询--------------------------
;WITH cte AS (
select cid,ctype,cqty,CASE WHEN sqty>=cqty THEN cqty ELSE sqty END AS qty ,sqty,sno ,ROW_NUMBER()OVER(PARTITION BY sno ORDER BY cqty DESC) id
from [CUT])
,cte1 AS
(
SELECT cid,ctype,cqty, qty ,sqty,sno,id
FROM cte
WHERE id=1
UNION ALL
SELECT a.cid,a.ctype,a.cqty,CASE WHEN b.sqty-b.cqty>=0 THEN b.sqty-b.cqty WHEN b.sqty-b.cqty<0 THEN 0 ELSE b.cqty END AS qty,CASE WHEN b.sqty-b.cqty>=0 THEN b.sqty-b.cqty ELSE b.cqty-b.qty END as sqty,a.sno,a.id
FROM cte a INNER JOIN cte1 b ON a.sno=b.sno AND a.id=b.id+1
)
SELECT cid, ctype, cqty , qty , sqty , sno
FROM cte1
ORDER BY cid
----------------结果----------------------------
/*
cid ctype cqty qty sqty sno
---- ----- ----------- ----------- ----------- -----
F21 0010 8 8 10 T1099
F22 0010 3 2 2 T1099
F23 0010 2 0 1 T1099
F31 0010 6 6 6 T8899
F32 0010 2 0 0 T8899
*/
------解决思路----------------------
你的意思是查每一行能满足CQTY的实际数量吧?
WITH cte AS
(
SELECT 'F21' AS CID,'0010' AS CTYPE,8 AS CQTY,NULL AS QTY,10 AS SQTY,'T1099' AS SNO
UNION ALL
SELECT 'F22','0010',3,NULL,10,'T1099'
UNION ALL
SELECT 'F23','0010',2,NULL,10,'T1099'
UNION ALL
SELECT 'F31','0010',6,NULL,6,'T8899'
UNION ALL
SELECT 'F32','0010',2,NULL,6,'T8899'
)
SELECT cte.* INTO [CUT] FROM cte
SELECT *
,CASE WHEN sqty>=c1.t_cqty THEN cqty
ELSE
CASE WHEN ABS(sqty-c1.t_cqty) >cqty THEN 0 ELSE cqty+sqty-c1.t_cqty END
END AS Qty
FROM CUT AS c CROSS APPLY
(SELECT ctype,sno,sum(cqty) AS t_cqty FROM CUT WHERE cid<=c.cid GROUP BY ctype,sno)
AS c1 WHERE c1.ctype=c.ctype AND c1.sno=c.sno