Sqlserver
 sql >> Base de données >  >> RDS >> Sqlserver

Requête SQL Server - multiplication par groupe

Multiplier les valeurs des lignes revient à ajouter les logarithmes des valeurs des lignes

L'astuce consiste à gérer les zéros et les valeurs nulles.

Ok, vérifié maintenant

DECLARE @foo TABLE (GrpID varchar(10), Value float)

INSERt @foo (GrpID, Value)
SELECT 'Grp1',          2
UNION ALL SELECT 'Grp1',          5
UNION ALL SELECT 'Grp1',          3
UNION ALL SELECT 'Grp2',          3
UNION ALL SELECT 'Grp2',         -5
UNION ALL SELECT 'Grp2',         -2
UNION ALL SELECT 'Grp3',          4
UNION ALL SELECT 'Grp3',          0
UNION ALL SELECT 'Grp3',          1
UNION ALL SELECT 'Grp4',         -2
UNION ALL SELECT 'Grp4',         -4
UNION ALL SELECT 'Grp5',          7
UNION ALL SELECT 'Grp5',       NULL
UNION ALL SELECT 'Grp6',       NULL
UNION ALL SELECT 'Grp6',       NULL
UNION ALL SELECT 'Grp7',         -1
UNION ALL SELECT 'Grp7',        10 

SELECT
    GrpID,
    CASE
       WHEN MinVal = 0 THEN 0
       WHEN Neg % 2 = 1 THEN -1 * EXP(ABSMult)
       ELSE EXP(ABSMult)
    END
FROM
    (
    SELECT
       GrpID, 
       --log of +ve row values
       SUM(LOG(ABS(NULLIF(Value, 0)))) AS ABSMult,
       --count of -ve values. Even = +ve result.
       SUM(SIGN(CASE WHEN Value < 0 THEN 1 ELSE 0 END)) AS Neg,
       --anything * zero = zero
       MIN(ABS(Value)) AS MinVal
    FROM
       @foo
    GROUP BY
       GrpID
    ) foo