SQL select中的减法返回0

时间:2019-04-03 13:00:20

标签: sql sql-server

我有一个查询(最后一列)之一应该是减去其他两列的结果。我的问题是,如果操作数之一为零,那么结果我也为零。 这是例子

SELECT 
#TmpDates.Date As Registration, 
ISNULL(Cr.NewSubscriptionsCount,0) As 'Initial Size',
ISNULL(U.UnsubsCount, 0) As 'Unsub. Count',
ISNULL(Cr.NewSubscriptionsCount - U.UnsubsCount, 0) As 'Alive count',
ISNULL(Cl.ClicksCount, 0) As Clicks,
CAST(ISNULL(C.Cost, 0) AS MONEY) As Cost,
CAST(ISNULL(P.Profit, 0) AS MONEY) As Revenue,
CAST(ISNULL((P.Profit - C.Cost), 0) AS MONEY) As Profit

FROM 

    #TmpDates 
    LEFT JOIN #TmpUnsubs U ON #TmpDates.Date = U.CreationDate   
    LEFT JOIN #TmpCreated Cr ON #TmpDates.Date = Cr.CreationDate
    LEFT JOIN #TmpClicks Cl ON #TmpDates.Date = Cl.SubscriptionCreationDate
    LEFT JOIN #TmpCost C ON #TmpDates.Date = C.CreationDate
    LEFT JOIN #TmpProfit P ON #TmpDates.Date = P.SubscriptionCreationDate

这是结果:

+------------+---+---+---+---+------+------+------+
| 2019-03-01 | 2 | 2 | 0 | 7 | 0.00 | 6.20 | 0.00 |
+------------+---+---+---+---+------+------+------+
| 2019-03-02 | 0 | 0 | 0 | 0 | 0.00 | 0.00 | 0.00 |
| 2019-03-03 | 1 | 1 | 0 | 0 | 0.00 | 0.00 | 0.00 |
| 2019-03-04 | 2 | 2 | 0 | 2 | 0.00 | 0.40 | 0.00 |
| 2019-03-05 | 1 | 1 | 0 | 0 | 0.00 | 0.00 | 0.00 |
| 2019-03-06 | 4 | 1 | 3 | 5 | 0.00 | 3.20 | 0.00 |
| 2019-03-07 | 4 | 4 | 0 | 0 | 0.00 | 0.00 | 0.00 |
| 2019-03-08 | 1 | 1 | 0 | 0 | 0.00 | 0.00 | 0.00 |
| 2019-03-09 | 3 | 1 | 2 | 8 | 0.00 | 2.90 | 0.00 |
| 2019-03-10 | 4 | 3 | 1 | 0 | 0.00 | 0.00 | 0.00 |
| 2019-03-11 | 3 | 3 | 0 | 0 | 0.00 | 0.00 | 0.00 |
| 2019-03-12 | 3 | 2 | 1 | 3 | 0.30 | 0.55 | 0.25 |
+------------+---+---+---+---+------+------+------+

1 个答案:

答案 0 :(得分:6)

其中一个是NULL时,您将得到0。您想要的是:

CAST(ISNULL(P.Profit, 0) - ISNULL(C.Cost, 0) AS MONEY)