Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a SUM() inside a case statement in SQL server

Tags:

sql

sql-server

I want to add some calculation inside my case statement to dynamically create the contents of a new column but I get the error:

Column 'Test1.qrank' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

This is the code I'm working on

case 
    when test1.TotalType = 'Average' then Test2.avgscore
    when test1.TotalType = 'PercentOfTot' then (cnt/SUM(test1.qrank))
    else cnt
end as displayscore

I did try to group but it didn't work.

Any hints?

like image 476
Athos Avatar asked Sep 27 '12 19:09

Athos


People also ask

Can we use SUM function in case statement?

Then comes the curious use of a SUM() with a CASE WHEN . This expression says whenever the number_of_lectures is higher than 20, the row is assigned the value 1. If the condition is not met, the assigned value is 0. The SUM() function will sum all those rows that have the assigned value equal to 1.

How do I sum values in SQL statement?

The aggregate function SUM is ideal for computing the sum of a column's values. This function is used in a SELECT statement and takes the name of the column whose values you want to sum. If you do not specify any other columns in the SELECT statement, then the sum will be calculated for all records in the table.

Can you put sum in a WHERE clause SQL?

SQL SUM() with where clause We can selectively find the sum of only those rows, which satisfy the given condition. To do this, we can use the where clause in the SQL statement.


1 Answers

The error you posted can happen when you're using a clause in the GROUP BY statement without including it in the select.

Example

This one works!

     SELECT t.device,
            SUM(case when transits.direction = 1 then 1 else 0 end) ,
            SUM(case when transits.direction = 0 then 1 else 0 end) from t1 t 
            where t.device in ('A','B') group by t.device

This one not (omitted t.device from the select)

     SELECT 
            SUM(case when transits.direction = 1 then 1 else 0 end) ,
            SUM(case when transits.direction = 0 then 1 else 0 end) from t1 t 
            where t.device in ('A','B') group by t.device

This will produce your error complaining that I'm grouping for something that is not included in the select

Please, provide all the query to get more support.

like image 146
Yngwie89 Avatar answered Sep 28 '22 02:09

Yngwie89