简体   繁体   English

SQL查询-总和行

[英]SQL Query - Sum Rows

I am attempting to calculate a value inside a view, from 2 rows on a table. 我试图从表中的2行计算视图内的值。 SQL Server. 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. 我想添加当前行的数量,如果另一行的TransferTo col等于当前行的RefId,则添加另一行的数量。

In the view I have: 我认为:

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

However, this is returning NULL . 但是,这将返回NULL

Would I better be using variables or a CAST function? 我最好使用变量还是CAST函数?

Thanks in advance for any input 预先感谢您的任何投入

The problem is that the subquery could be returning NULL . 问题是子查询可能返回NULL This is a case where ISNUL() is preferable over COALESCE() : 在这种情况下, ISNUL()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 .) (这假设外部查询的表别名为t 。)

ISNULL() is preferable because COALESCE() might evaluate the subquery twice, which is unnecessary overhead. ISNULL()是可取的,因为COALESCE()可能会两次评估子查询,这是不必要的开销。 (Otherwise, I prefer COALESCE() because it is the ANSI standard function.) (否则,我更喜欢COALESCE()因为它是ANSI标准函数。)

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 . 你会得到价值为NULL ,同时增加2个值如果任一值的是NULL So Use the ISNULL() on both sides to avoid the NULL . 因此,在两侧都使用ISNULL()可以避免使用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

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

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