sql >> Base de Datos >  >> RDS >> Sqlserver

operación de resta en dos filas de la tabla temporal en el servidor SQL

SELECT
  [qid1].AgeBelow16 - [qid2].AgeBelow16       AS [AgeBelow16],
  [qid1].Age16_20   - [qid2].Age16_20         AS [Age16_20],
  [qid1].Age21_30   - [qid2].Age21_30         AS [Age21_30],
  [qid1].Age31_40   - [qid2].Age31_40         AS [Age31_40],
  [qid1].Age41_50   - [qid2].Age41_50         AS [Age41_50],
  [qid1].Age51_60   - [qid2].Age51_60         AS [Age51_60]
FROM
  MyTable AS [qid1]
INNER JOIN
  MyTable AS [qid2]
    ON [qid1].QID = [qid2].QID - 1
WHERE
  [qid1].QID = 1

Sin embargo, si es posible, sería mucho mejor almacenar los valores QID2 como negativos. De esa manera, no necesita saber cuál restar del otro; es solo una SUMA directa.

SELECT
  SUM(AgeBelow16) AS [AgeBelow16],   -- (93) + (-13) = 80
  SUM(Age16_20)   AS [Age16_20],     -- (81) + (-11) = 70
  SUM(Age21_30)   AS [Age21_30],     -- (55) + (-15) = 40
  SUM(Age31_40)   AS [Age31_40],     -- (46) + (-16) = 30
  SUM(Age41_50)   AS [Age41_50],     -- (54) + (-14) = 40
  SUM(Age51_60)   AS [Age51_60]      -- (48) + (-18) = 30
FROM
  MyTable