Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Standard method for MySQL's IF() function

I have found MySQL's IF() function to be very useful in giving me an efficient way to do conditional aggregate functions, like this:

SELECT SUM(IF(`something`='a', `something_weight`, 0)) AS `A`, SUM(`something_weight`) AS `All` FROM...

It is my understanding that this function is a feature of MySQL, and is not generally available in databases that use SQL.

Is there a more standard method to achieve this functionality on the database side of things?

like image 685
Brad Avatar asked Feb 28 '11 14:02

Brad


2 Answers

I'm not a sql guru but case statement

http://dev.mysql.com/doc/refman/5.0/en/case-statement.html

might be standard ansi.

like image 75
Nicola Cossu Avatar answered Sep 22 '22 03:09

Nicola Cossu


I believe using a CASE statement would be more standard.

SELECT SUM(CASE `something` WHEN 'a' THEN `something_weight` ELSE 0 END) AS `A`, 
       SUM(`something_weight`) AS `All` 
    FROM...
like image 40
Joe Stefanelli Avatar answered Sep 20 '22 03:09

Joe Stefanelli