Ert - 2 years ago 135
SQL Question

# How make sum using some conditions in sql?

I have a user table like this

``````  ID     Date        Value
---------------------------
1001   31 01 14    2035.1
1002   31 01 14    1384.65
1003   31 01 14    1011.1
1004   31 01 14    1187.04
1001   28 02 14    2035.1
1002   28 02 14    1384.65
1003   28 02 14    1011.1
1004   28 02 14    1188.86
1001   31 03 14    2035.1
1002   31 03 14    1384.65
1003   31 03 14    1011.1
1004   31 03 14    1188.86
1001   30 04 14    2066.41
1002   30 04 14    1405.95
1003   30 04 14    1026.66
1004   30 04 14    1207.15
``````

And I want to make a sum from this table like this

``````  ID     Date        Value       Total
---------------------------------------
1001   31 01 14    2035.1     2035.1
1002   31 01 14    1384.65    1384.65
1003   31 01 14    1011.1     1011.1
1004   31 01 14    1187.04    1187.04
1001   28 02 14    2035.1     4070.2
1002   28 02 14    1384.65    2769.3
1003   28 02 14    1011.1     2022.2
1004   28 02 14    1188.86    2375.9
1001   31 03 14    2035.1     6105.3
1002   31 03 14    1384.65    4153.95
1003   31 03 14    1011.1     3033.3
1004   31 03 14    1188.86    3564.76
1001   30 04 14    2066.41    8171.71
1002   30 04 14    1405.95    5180.61
1003   30 04 14    1026.66    4059.96
1004   30 04 14    1207.15    4771.91
``````

I have id, for each id for the first month it should write it is value for total and for second month of that id it should add the value of first month + second month and it should go on like this. How can I do this summation in SQL?

Can anyone save my day?

Try this

``````SELECT
ID,
[Date],
Value,
Total = Value + COALESCE(
(
SELECT SUM(Value)
FROM TableName AS s
WHERE s.[Date] < o.[Date] AND s.Id=o.Id), 0
)
FROM TableName AS o
ORDER BY [Date];
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download