Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

calculate Row Wise Sum - Sql server

This is My table :

ID              Q1         Q2           Q3            Q4
----------------------------------------------------------------
20130712        NULL       728.63       NULL            NULL
20130712        8881.55    9673.68      2629.566        6251.984
20130713        1813       1813         84.49           1728.51
20130714        3632.65    3632.65      1209.412        2423.238
20130714        70.758     2637.43      70.758          0
20130714        1601.578   3569.73      204.745         1396.833
20130714        728.63     728.63       0               728.63
20130714        1401.629   2251.39      94.418          1307.211
20130715        583.956    5089.19      583.956         0
20130805        6317.277   8958         2629.566        3687.711

I want the output like below.(The columns might change dynamically, needs to calculate Sum by row wise)

ID              Q1         Q2           Q3            Q4             SUM(Q1:Q4)
---------------------------------------------------------------------------
20130712        NULL       728.63       NULL            NULL         728.63   
20130712        8881.55    9673.68      2629.566        6251.984     27436.78
20130713        1813       1813         84.49           1728.51      5439
20130714        3632.65    3632.65      1209.412        2423.238     ...
20130714        70.758     2637.43      70.758          0
20130714        1601.578   3569.73      204.745         1396.833
20130714        728.63     728.63       0               728.63
20130714        1401.629   2251.39      94.418          1307.211
20130715        583.956    5089.19      583.956         0
20130805        6317.277   8958         2629.566        3687.711
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You haven't shown your query attempt, but it's probably something like this:

SELECT
  ID, Q1, Q2, Q3, Q4,
  Q1 + Q2 + Q3 + Q4 AS "Total"
FROM MyTable

If any of the Q1, Q2, Q3, or Q4 values are null, Q1 + Q2 + Q3 + Q4 will be null. To treat the nulls as zero and get a proper sum, do this instead:

SELECT
  ID, Q1, Q2, Q3, Q4,
  COALESCE(Q1,0) + COALESCE(Q2,0) + COALESCE(Q3,0) + COALESCE(Q4,0) AS "Total"
FROM MyTable

The COALESCE function will return the first non-null value in the list.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...