即使列为false / true,也要获得总和

时间:2016-01-02 19:25:14

标签: sql tsql

我有2列(时间和材料),我想总结一下。 问题是,如果我的数据是" True"我只得到总和。在他们两个。所以,如果我有时间,那就是" True"并且只获得了#34; False"我一无所获。请帮忙

 SELECT ((SELECT ROUND(SUM([Time]*[Price]),0)  FROM [tblTime] Y WHERE Y.[OwnerId] = <ID> AND Y.[Invoice] = 'True') 
+
(SELECT ROUND(SUM([Amount]*[Price]),0)  FROM [tblMaterial] M WHERE M.[OwnerId] = <ID> AND M.[Invoice] = 'True'))

2 个答案:

答案 0 :(得分:0)

如果您的某个字段不是True,则您在此组件中有效获得NULL值,当您添加NULL时,任何数字的结果始终为NULL

要解决此问题,您可以使用函数COALESCE确保如果您的值为NULL,则COALESCE使用后备值0

SELECT COALESCE(
    (SELECT ROUND(SUM([Time]*[Price]),0)  
     FROM [tblTime] Y 
     WHERE Y.[OwnerId] = <ID> AND Y.[Invoice] = 'True')
    , 0)    -- value 0 is used only if SELECT returns NULL
+
COALESCE(
    (SELECT ROUND(SUM([Amount]*[Price]),0)  
     FROM [tblMaterial] M 
     WHERE M.[OwnerId] = <ID> AND M.[Invoice] = 'True')
    , 0)    -- value 0 is used only if SELECT returns NULL

答案 1 :(得分:0)

可能存在NULL

的问题
 SELECT (
    ISNULL(
       SELECT ROUND(SUM([Time]*[Price]),0)  
       FROM [tblTime] Y
       WHERE Y.[OwnerId] = <ID> AND Y.[Invoice] = 'True'
       , 0) 
    +
    ISNULL(
        SELECT ROUND(SUM([Amount]*[Price]),0) 
        FROM [tblMaterial] M 
        WHERE M.[OwnerId] = <ID> AND M.[Invoice] = 'True'
        , 0)
    )