sql >> データベース >  >> RDS >> Sqlserver

T-SQL での乗算の実行

    次のソリューションでは、四半期ごとに常に 3 行 (最後の四半期のみが部分的である可能性があります)、単一の SELECT、再帰がないことを前提としています :-)

    WITH sumQuart AS
     (
       SELECT *,
          CASE
            WHEN ROW_NUMBER() -- for the 1st month in a quarter
                 OVER (PARTITION BY CCP, Years, Quart
                       ORDER BY months) = 1
                      -- return the sum of all GTS of this quarter
            THEN SUM(GTS) OVER (PARTITION BY CCP, Years, Quart)
            ELSE NULL -- other months
          END AS sumGTS
       FROM gts
     )
    ,cte AS
     (
       SELECT 
          sq.*,
          COALESCE(b.Baseline, -- 1st quarter
                   -- product of all previous quarters
                   CASE
                     WHEN MIN(ABS(sumGTS)) -- any zeros?
                          OVER (PARTITION BY sq.CCP ORDER BY sq.Years, sq.Quart, sq.Months 
                                ROWS BETWEEN UNBOUNDED PRECEDING AND 3 PRECEDING) = 0 
                       THEN 0  
                     ELSE -- product
                          EXP(SUM(LOG(NULLIF(ABS(COALESCE(b.Baseline,1) * sumGTS),0)))
                              OVER (PARTITION BY sq.CCP ORDER BY sq.Years, sq.Quart, sq.Months 
                                    ROWS BETWEEN UNBOUNDED PRECEDING AND 3 PRECEDING)) -- product
                          -- odd number of negative values -> negative result
                        * CASE WHEN COUNT(CASE WHEN sumGTS < 0 THEN 1 END) 
                                    OVER (PARTITION BY sq.CCP ORDER BY sq.Years, sq.Quart, sq.Months 
                                          ROWS BETWEEN UNBOUNDED PRECEDING AND 3 PRECEDING) % 2 = 0 THEN 1 ELSE -1 END
                   END) AS newBaseline
       FROM sumQuart AS sq
       LEFT JOIN BASELINE AS b
              ON B.CCP = sq.CCP
              AND b.Quart = sq.Quart
              AND b.Years = sq.Years
     )
    SELECT 
       CCP, months, Quart, Years, GTS,
       round(newBaseline * GTS,2),
       round(newBaseline,2)
    FROM cte
    

    フィドル を参照してください

    編集:値を処理するロジックを追加 <=0 フィドル



    1. 未定義のインデックス:C:\ wamp \ www \ Website \ storeadmin \admin_login.php..のユーザー名とパスワードも同じ

    2. SQLServerで大文字を含む行を見つける5つの方法

    3. SQLとMySQLの違いは何ですか

    4. 行ごとのNull変数の数をカウントしますmysql