試してみてください:
DECLARE @t TABLE ( ID INT , wac DECIMAL(30, 10) , item CHAR(1) )DECLARE @b TABLE ( item CHAR(1) , ベースライン DECIMAL(30, 10) )INSERT INTO @ tVALUES ( 1, 2.31, 'A' ), ( 2, 1.10, 'A' ), ( 3, 2.13, 'A' ), ( 4, 1.34, 'A' )INSERT INTO @bVALUES ( 'A', 10 );WITH ordercte AS ( SELECT * , ROW_NUMBER() OVER ( PARTITION BY item ORDER BY ID ) AS rn FROM @t ), rec AS ( SELECT t.item , t.ID , t.wac , t.rn , b.ベースライン * ( 1 + ( t.wac / 100 ) ) AS m FROM ordercte t JOIN @b b ON b.item =t.item WHERE t.rn =1 UNION ALL SELECT t.item , t.ID , t.wac , t.rn , cm * ( 1 + ( t.wac / 100 ) ) FROM ordercte t JOIN rec c ON t.item =c.item AND t.rn =c.rn + 1 ) SELECT id , wac , item , m FROM rec
プレ>出力:
id wac item m1 2.3100000000 A 10.2310002 1.1000000000 A 10.3435413 2.1300000000 A 10.5638584 1.3400000000 A 10.705414
プレ>EDIT1
私は LOG EXP トリックを実装しようとしていましたが、@usr が私を解決策に導かない限り管理できませんでした。したがって、すべてのクレジットはユーザー @usr にあります:
WITH ordercte AS ( SELECT t.ID , t.wac , t.item , b.baseline , ROW_NUMBER() OVER ( PARTITION BY t.item ORDER BY ID ) AS rn FROM @t t JOIN @b b ON b.item =t.item ) SELECT ベースライン * EXP(SUM(LOG(( 1 + ( wac / 100 )))) OVER ( PARTITION BY item ORDER BY rn )) AS m FROM ordercte
プレ>または単に:
SELECT t.ID, t.wac, t.item,baseline * EXP(SUM(LOG(( 1 + ( wac / 100 )))) OVER ( PARTITION BY t.item ORDER BY t.ID )) AS mFROM @t t JOIN @b b ON b.item =t.item
プレ>ID が注文のフィールドである場合。
出力:
ID wac item m1 2.3100000000 A 10.2312 1.1000000000 A 10.3435413 2.1300000000 A 10.56385842334 1.3400000000 A 10.7054141261722
プレ>EDIT2
SQL 2008 の場合:
WITH cte AS ( SELECT t.ID , t.wac , t.item ,baseline , ( SELECT SUM(LOG(( 1 + ( wac / 100 ) ))) FROM @t it WHERE it.item =t.item AND it.ID <=t.ID ) AS e FROM @t t JOIN @b b ON b.item =t.item ) SELECT ID、wac、item、baseline * EXP(e) AS m FROM cteコード> プレ>
EDIT3
NULL と負の値でダイヤルする SQL Server 2008 の完全なソリューションを次に示します。
WITH cte AS ( SELECT t.ID , t.wac , t.item , b.baseline , ca.e, ca.n, ca.m FROM @t t JOIN @b b ON b.item =t .item CROSS APPLY(SELECT SUM(LOG(ABS(NULLIF( 1 + wac / 100 , 0)))) as e, SUM(SIGN(CASE WHEN 1 + wac / 100 <0 THEN 1 ELSE 0 END)) AS n , MIN(ABS(1 + wac / 100)) AS m FROM @t it WHERE it.item =t.item AND it.ID <=t.ID ) ca ) SELECT ID、wac、item、baseline * CASE WHEN m =0 THEN 0 WHEN n % 2 =1 THEN -1 * EXP(e) ELSE EXP(e) END as Result FROM cte
プレ>