开发者

Standard method for MySQL's IF() function

I have found MySQL's IF() function to be very useful in giv开发者_运维知识库ing 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?


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.


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...


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


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 ...


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜