简体   繁体   English

如何在多列上使用MySql SUM()

[英]How to use MySql SUM() on multiple columns

I am struggling with MySql SUM() function . 我在MySql SUM()函数中苦苦挣扎。 For example , I have a table called my_table with columns('id','price_1','price_2') . 例如,我有一个名为my_table的表,其中包含columns('id','price_1','price_2')。 I know this table is not following 1st normalization . 我知道此表不遵循1st规范化。 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 : 使用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 . 如果price_2NULLCOALESCE将采用price_1 ie, COALESCE will return the first parameter which is not NULL . 即, COALESCE将返回不为NULL的第一个参数。

Sample result in SQL Fiddle SQL Fiddle中的样本结果

If you want to find the sum of price_1 when all the price_2 are NULL . 如果要在所有price_2均为NULL时找到price_1的总和。 Then: 然后:

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

Sample result in SQL Fiddle SQL Fiddle中的样本结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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