mosiki
mosiki

Reputation: 21

SQL Query - Sum Rows

I am attempting to calculate a value inside a view, from 2 rows on a table. SQL Server.

The table has these columns

----------------------------------------------
|RefId | Quantity | TransferFrom | TransferTo |
----------------------------------------------
|5601  | 100      | 5580         | null       |
-----------------------------------------------
|5850  | 200      | null         | 5601       |
-----------------------------------------------

I would like to add the quantity of the current row, and the quantity of another row if the other row's TransferTo col equals the current row's RefId.

In the view I have:

MyAmount = [Quantity] + (SELECT [Quantity] 
                         FROM MyTable  
                         WHERE [TransferTo] = [RefId])

However, this is returning NULL.

Would I better be using variables or a CAST function?

Thanks in advance for any input

Upvotes: 0

Views: 68

Answers (3)

Nolan Shang
Nolan Shang

Reputation: 2328

Do you want get this result?

 ;WITH MyTable(RefId,Quantity,TransferFrom,TransferTo) AS(
      SELECT 5601,100,5580,null UNION ALL 
      SELECT 5850 ,200,null , 5601
)
SELECT x.*,MyAmount = x.[Quantity]+ISNULL( y.[Quantity] ,0)

FROM MyTable x
LEFT JOIN MyTable  AS y ON x.TransferTo=y.RefId
RefId   Quantity    TransferFrom    TransferTo  MyAmount
5601    100 5580    NULL    100
5850    200 NULL    5601    300

Upvotes: 0

Jayasurya Satheesh
Jayasurya Satheesh

Reputation: 8033

You Will Get the Value as NULL while adding 2 values if either of the value is NULL. So Use the ISNULL() on both sides to avoid the NULL.

MyAmount = ISNULL([Quantity],0.00) + ISNULL((SELECT [Quantity] 
                         FROM MyTable  
                         WHERE [TransferTo] = [RefId]),0.00)

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1269463

The problem is that the subquery could be returning NULL. This is a case where ISNUL() is preferable over COALESCE():

MyAmount = ([Quantity] +
            ISNULL((SELECT t2.[Quantity] FROM MyTable t2 WHERE t2.[TransferTo] = t.[RefId]), 0)
           )

(This assumes that the table alias from the outer query is t.)

ISNULL() is preferable because COALESCE() might evaluate the subquery twice, which is unnecessary overhead. (Otherwise, I prefer COALESCE() because it is the ANSI standard function.)

Note: If you are using correlated subqueries, you should always qualify all your column names.

Upvotes: 2

Related Questions