简体   繁体   中英

How to use MySql SUM() on multiple columns

I am struggling with MySql SUM() function . For example , I have a table called my_table with columns('id','price_1','price_2') . I know this table is not following 1st normalization . But I need to just to demonstrate what I am in need . I want to select like this .

SELECT SUM({price_1 if price_2 is null}) GROUP BY `id`

How can I achieve this?

Use COALESCE :

SELECT SUM(COALESCE(price_2,price_1)) as TotalPrice
FROM my_table 
GROUP BY `id`

COALESCE will take price_1 if price_2 is NULL . ie, COALESCE will return the first parameter which is not NULL .

Sample result in SQL Fiddle

If you want to find the sum of price_1 when all the price_2 are NULL . Then:

SELECT COALESCE(SUM(price_2),SUM(price_1)) as TotalPrice
FROM my_table 
GROUP BY `id`

Sample result in SQL Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM