两列的总和在php mysql

时间:2015-08-21 07:51:03

标签: sql-server

我想输出0而不是NULL

Here Is Link For Example

CREATE TABLE Table1
    ([id] int, [pid] int, [cid] int, [NetAmount] int)
;

INSERT INTO Table1
    ([id], [pid], [cid],[NetAmount])
VALUES
    (1, 1,2, 20),
    (1, 1,2, 20),
    (1, 1,2, 20),
    (1, 1,2, 20),
    (1, 1,2, 20),
    (1, 1,2, 20);


select 
   ( select sum(NetAmount) 
    from Table1 
    where pid = '1') - 

    ( select sum(NetAmount) 
    from Table1 
    where cid = '1')

3 个答案:

答案 0 :(得分:0)

您可以使用ISNULL()功能:

select ( select ISNULL(sum(NetAmount) ,0)
         from Table1 
         where pid = '1') -                 
       ( select ISNULL(sum(NetAmount),0)
         from Table1 
         where cid = '1')

答案 1 :(得分:0)

null应用于任何算术运算将导致null。您可以使用coalesce函数解决此问题:

select 
   ( select coalesce(sum(NetAmount), 0) 
    from Table1 
    where pid = '1') - 

    ( select coalesce(sum(NetAmount), 0) 
    from Table1 
    where cid = '1')

答案 2 :(得分:0)

select 
       ( select isnull(sum(NetAmount),0)
        from Table1 
        where pid = '1') - 

        ( select isnull(sum(NetAmount),0) 
        from Table1 
        where cid = '1')