简体   繁体   中英

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

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.

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)

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

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