7

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?

Brad
  • 159,648
  • 54
  • 349
  • 530

5 Answers5

3

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.

Nicola Cossu
  • 54,599
  • 15
  • 92
  • 98
2

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...
Joe Stefanelli
  • 132,803
  • 19
  • 237
  • 235
2

CASE is the general command you can use to do conditional aggregate functions. For more info see http://www.1keydata.com/sql/sql-case.html

Tanner
  • 21
  • 1
1

In MSSQL you can do this:

SELECT SUM(CASE something WHEN 'a' THEN something_weight ELSE 0 END) as [a],
       SUM(something_weight) as [All]
FROM ...
Johan
  • 1,152
  • 7
  • 16
1

look at using CASE: CASE (Transact-SQL)

SELECT SUM(CASE WHEN something='a' THEN XXX WHEN something='b' THEN YYY ELSE 0 END ) AS ColumnName

RacerX
  • 2,566
  • 3
  • 23
  • 21