3

For example, I have the following table:

date | id | num
01-01 | a | 10
01-02 | a | 14
01-02 | b | 2
01-03 | a | 19
01-03 | b | 5
01-04 | a | 13

I want to substract num of b from a, that is, the result will be:

01-01 | 10    //10
01-02 | 12    //14-2
01-03 | 14    //19-5
01-04 | 13    //13

I tried the following SQL query but if there is no record of b on a date, it will return \N.

SELECT tba.date, numall-numout
FROM (
    SELECT date, num AS numall
    FROM tb
    WHERE id = "a"
) tba
LEFT JOIN (
    SELECT date, num AS numout
    FROM tb
    WHERE id = "b"
) tbb
ON tba.date = tbb.date
4

2 回答 2

7

如果没有匹配的 B,左连接将返回 null,这意味着你正在做

numall - NULL

这导致NULL。为了解决这个问题,你必须做

numall - COALESCE(numout, 0)

对不存在的“b”日期强制为 0。

于 2012-04-12T18:07:58.407 回答
0

利用SELECT tba.date, numall-ISNULL(numout,0)

于 2012-04-12T18:08:55.597 回答