如何在SQL

时间:2019-06-12 08:58:47

标签: sql

当我尝试获取三列的总和作为总数时,如果在Recieved,Claim或Issue中某一列为null,则为null

SELECT YarnId,
Recieve,
Issued,
Claim,
Total=Recieve+Issued
FROM
(
SELECT YarnId,Status,Bags
FROM Yarn_IssueRecieve
) as PivotData

Pivot
(
SUM(bags) for Status in (Recieve,Issued,Damage,Claim)
) as Pivoting

以下是输出

enter image description here

3 个答案:

答案 0 :(得分:0)

使用COALESCE

Total= COALESCE (Recieve,0) + COALESCE (Issued,0)

SUM( COALESCE (bags,0) )

答案 1 :(得分:0)

您可以使用ISNULL

SELECT YarnId,
Recieve,
Issued,
Claim,
Total=ISNULL(Recieve,0)+ISNULL(Issued,0)
FROM
(
SELECT YarnId,Status,Bags
FROM Yarn_IssueRecieve
) as PivotData

Pivot
(
SUM(bags) for Status in (Recieve,Issued,Damage,Claim)
) as Pivoting

答案 2 :(得分:0)

在MySql或MSSQL Server中,如果添加任何带NULL的数字,则结果为NULL。例如-

SELECT 10 + NULL
--Result is NULL

因此,您可以在查询中使用NULL来解决所面临的问题。您可以根据需要使用COALESCE,脚本应如下所示-

Total=COALESCE(Recieve,0)+COALESCE(Issued,0)