How to "prefer" data from one table over another in SQL, help reformulating.

StackOverflow https://stackoverflow.com/questions/23679021

  •  23-07-2023
  •  | 
  •  

سؤال

Using Sql management Studio on Sql-Server 2005.

I guess my title is not very clear, so although I'd appreciate a direct answer, even better would be help in reformulating the question that I can search for an answer by myself and learn in the process.

Table A contains yearly total sales for various products. This table is updated once a year in Feb/March.There are two consequences to that: A product that started being sold in, say, July, will obviously only have a six month sale total for the year. Also, any new product will not appear in it before the following year.

Table B is an exception table that gives an estimate for all products not yet in table A or that have a less than a twelve months sale history.

Table C joins the yearly sales with various info from other tables and also contains calculated columns .

In pseudo code what I need is:

Use sales of product x from Table A in table C unless sales for this product exist in table B.

Basically, data from table B should take precedence over table A wether the record exists in A or not.

هل كانت مفيدة؟

المحلول

If you do a LEFT JOIN and no records exist in B, you will get a null for the column values in B. So to "prefer" valued that exist in B, use COALESCE:

SELECT COALESCE(B.Sales, C.Sales) AS Sales
FROM ...

Which loosely translates to "If B has a Sales value, use it, otherwise use the value from C."

Technically it means "take the first non-null value from B.Sales and C.Sales (in that order)"

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top