0

I have bids table with two bids price columns bidsprice1 and bidsprice2. and all users have bidsprice1 amount, and some users also have bidsprice2 amount.

I want to calculate sum(bidsprice2) based on bidsprice2, if some users have null bidsprice2, then based on its bidsprice1.

How to write this sum query?

2 Answers 2

1

Use COALESCE() to return the first non-NULL argument. That can be wrapped directly inside the aggregate SUM(). This has the advantage of being able to add additional columns if the need arises.

SELECT /* SUM() based on bidsprice2 if non-null, bidsprice1, or finally 0 if both NULL */ SUM(COALESCE(bidsprice2, bidsprice1, 0)) AS your_sum FROM yourtable 
Sign up to request clarification or add additional context in comments.

Comments

0
SUM(CASE WHEN bidsprice2 IS NULL THEN bidsprice1 ELSE bidsprice2 END) 

In MySQL

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.