如何在sqlserver中将聚合空值表示为0

时间:2018-02-02 19:03:07

标签: sql-server

我需要聚合空值以在输出中显示为0.

您可以在这里查看sql代码http://sqlfiddle.com/#!18/ff1d4/4

CREATE TABLE Customers (
    CustomerId int PRIMARY KEY,
    Name varchar(255)
);

CREATE TABLE Orders (
    OrderId int PRIMARY KEY,     
    CustomerId int FOREIGN KEY REFERENCES Customers(CustomerId),
    Amount INT
);

insert into Customers values(1, 'Peter');
insert into Customers values(2, 'Paul');
insert into Customers values(3, 'Mary');

insert into Orders values(1,1,100);
insert into Orders values(2,2,200);
insert into Orders values(3,1,300);

select c.customerid,name,count(orderId) OrderCount, ISNULL(sum(amount),0) TotalAmount 
from customers c 
  JOIN orders o on c.customerid = o.customerid
group by C.customerid,NAME;


customerid  name    OrderCount  TotalAmount
1   Peter   2   400
2   Paul    1   200

我的输出应该如下所示

customerid     name     ordercount   totalamount

 1             peter       2            400
 2             paul        2            400
 3             mary        0            0

我的查询没有获得最后一行

任何帮助?

0 个答案:

没有答案