Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CONDITIONAL SUM T-SQL

I have a table in this format

COL1 COL2 COL3
A    NULL  4
A    NULL  4
A    VAL1  4
A    VAL2  4
A    VAL3  4
B    NULL  5
B    VAL1  6

I need to bring out the output as follows:

COL1 TOTAL VALID
A    20     12
B    11     6

My Question is, how do I get the 'VALID' column - it should do sum of col3 only if col2 is not null.

I was able to get the 'TOTAL' field correctly using SUM and group by clauses. But how do I compute the 'VALID' column?

Any ideas? Thanks a lot!

like image 530
Sekhar Avatar asked Jan 14 '11 15:01

Sekhar


People also ask

How do I condition a sum in SQL?

A method to simplify this query and to run within a single select that I have used with success is to use a “conditional” sum in the SQL query. So rather than running COUNT(*) we will be running SUM(…) . We will combine the SUM() call with a CASE statement, so that it counts correctly.

Can we use sum function in case statement?

A CASE WHEN expression is often used with a SUM() function in more complex reports, which can be quite challenging for beginners. Even though you're probably used to using the SUM() function for summing values, it can also be used for counting. This example will help you understand the concept better.

Is there a sum function in SQL?

The SQL Server SUM() function is an aggregate function that calculates the sum of all or distinct values in an expression. In this syntax: ALL instructs the SUM() function to return the sum of all values including duplicates. ALL is used by default.

Does SQL have conditional statements?

Conditional statements are used to define what logic is to be executed based on the status of some condition being satisfied. There are two types of conditional statements supported in SQL procedures: CASE.


1 Answers

Something like this:

SELECT col1
     , SUM(col3) AS TOTAL
     , SUM(CASE WHEN col2 IS NOT NULL THEN col3 ELSE NULL END) AS VALID
  FROM mytable
 GROUP BY col1

The "trick" is to use the CASE expression to conditionally return the value of col3.

like image 101
spencer7593 Avatar answered Sep 22 '22 04:09

spencer7593