|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
Conditionally Suming Rows
What I have is two columns that I want to sum. I'll call these columns A and column B. I want to Sum the values of Column A but only if the Column B is 0 or Null. Lets say I have:
Code:
ColumnA Column B ----------------------------- 100 300 100 0 100 0 Results: Sum(ColumnA) = 200, Sum(ColumnB) = 300 Is it possible to do this with a query? Or do i need to use a Stored Procedure. The query itself is actually much more complicated than what I have shown, but I am just trying to get the concept. I know that I could simply erase the ColumnA value when a ColumnB value is entered, but the number at ColumnA is still valuable information. It doesn't seem to make sense to me that I would have to delete it. I also thought about do another query that just selected rows where columb B has a value, and subtracting that sum from the total sum of all rows, while this would work I can't seem to figure out how I would even implement that. |
|
#2
|
|||
|
|||
|
Easy:
Code:
SELECT SUM(
CASE
WHERE [Column B] = 0 OR [Column B] IS NULL THEN 0
ELSE [Column A]
END) AS sum_Column_A
,SUM([Column B]) AS sum_Column_B
FROM YourTable
if you want just Column A (you can still use the above query, or...) Code:
SELECT SUM([Column A]) AS sum_Column_A FROM YourTable WHERE [Column B] != 0 AND [Column B] IS NOT NULL |
|
#3
|
|||
|
|||
|
Thanks. Works like a charm.
|
![]() |
| Viewing: Dev Shed Forums > Databases > MS SQL Development > Conditionally Suming Rows |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|
|