表格1: 6 d4 T- U ^* t# n3 G2 o5 q! `ARTIKEL SUPPLIERID SALE_SUM_PIECES TV SONY 表2:3 @+ ]3 N8 s( P: ^; f$ @
ROW_ID ARTIKEL SUPPLIERID PIECES TV SONY 6 TV SONY 10 3 TV SONY TV SONY 14 5555 TV SONY TV SONY 4我只需要在值TABLE1。“ SALE_SUM_PIECES”小于TABLE2中“' o/ K" b4 \2 t2 v N( D
PIECES总和时减去X=23onTABLE2."IECES"例如:值TABLE1."SALE_SUM_PIECES"现在,我需要检查7。goes lessthanSUM值在哪一行?TABLE2."IECES"。在以下示例中,TABLE第二行无效,因为7大于6。TABLE2中的第二行是有效的,因为row1中块的总和TABLE2中的row2即6 6 | u! q9 e0 C8 L! e J 10 = 16大于7。因此,我需要X=23从第二行减去后续行的值TABLE2.我的查询如下: , P0 F8 L6 t3 ^6 c1 y0 f3 x9 ]! i1 pSELECT "SUPPLIERID","ARTIKEL", (case when ( cumulativesum - (select "SALE_SUM_PIECES" from T1 where T1."SUPPLIERID"=T2."SUPPLIERID" and T1."ARTIKEL" = T2."ARTIKEL" )) 0 then (case when @x - cumulativesum 0 then 0 when @x - "cumulativesum" 当我执行上述查询时,我得到的结果如下:7 q9 u" O* E6 G3 q. E2 @
ROW_ID ARTIKEL SUPPLIERID PIECES VALUE_DRILL_DOWN TV SONY 6 NULL 2 TV SONY TV SONY 6 1 4 TV SONY 14 TV SONY Null 6 TV SONY 4 Null但希望结果如下: % y( E }" R- C; B$ i# \ ROW_ID ARTIKEL SUPPLIERID PIECES VALUE_DRILL_DOWN TV SONY 6 NULL 2 TV SONY TV SONY TV SONY TV SONY 188 18 Null 6 TV SONY 4 4 Null我希望从表2中(条件)TABLE1."SALE_SUM_PIECES" 3 g- W$ U t# Q ^提前致谢。 & D R# e$ K; K' i- | 7 ]9 j- q+ ^! K7 x* ] 解决方案: ) G" p0 g e; R
以下解决方案可以下解决方案。SqlFiddle% F, I, w- @, ?* `/ W, c
1 TV SONY 922 6 110 2.50 NULL2 TV SONY 10 80 10 80 .000 1333 TV SONY 922 65 .50 74 TV SONY 922 14 95 .50 505 505 TV SONY 922 18 95 .50 NULL6 TV SONY 922 4 95 15 .50 NULLDECLARE @x INT = 23; WITH cte AS( SELECT t2.*,t1.SALE_SUM_PIECES, CASE WHEN SUM(t2.PIECES) OVER (PARTITION BY t2.ARTIKEL,t2.SUPPLIERID ORDER BY ROW_ID) 0 THEN WHEN @x - CumulativeSum <= 0 THEN NULL ELSE @x - CumulativeSum END AS VALUE_DRILL_DOWNFROM cumulative