SUM (TSQL Function)

Returns the sum of the column values.

Syntax

SUM ( expression )

Arguments

expression
is a numeric expression of type bit, tinyint, smallint, int, bigint, money, numeric, float.

Return Types

For integer expression, returns bigint.

For money or float expression, returns the same type.

For numeric expression, returns numeric with same scale but max precision.

Remarks

NULL values are ignored.

Examples

DECLARE @t TABLE (
    id         INT NOT NULL PRIMARY KEY,
    name       VARCHAR(30),
    birthdate  DATE,
    children   TINYINT
);

INSERT INTO @t VALUES (10, 'John',  '19700301', 1),
                      (20, 'Fred',  '20021123', NULL),
                      (40, 'Alex',  '19950712', 2),
                      (50, 'Maria', '19700322', 0),
                      (30, 'Alice', '19950101', NULL),
                      (15,  NULL,   '19950101', 5);

SELECT YEAR(birthdate), SUM(children), COUNT(*)
FROM @t
GROUP BY YEAR(birthdate)
ORDER BY YEAR(birthdate);

The result is:

$g$0       |$sum$1              |$count$2   |
-----------+--------------------+-----------+
       1970|                   1|          2|
       1995|                   7|          3|
       2002|              <NULL>|          1|

(3 row(s) affected)
RSQL, a simple alternative to Microsoft SQL Server