我有下表:
create table #tbl
(
[type] varchar(20),
[qty] int
)
insert into #tbl values ('Type A', 10)
insert into #tbl values ('Type A', 15)
insert into #tbl values ('Type B', 5)
insert into #tbl values ('Type B', 8)
现在我想显示每个“类型”的总数量:
select
isnull([type], 'Other') as [type],
sum(case
when [type] = 'Type A' then qty
when [type] = 'Type B' then qty
when [type] = 'Type C' then qty
else 0
end) as [total]
from #tbl
where [type] in ('Type A', 'Type B', 'Type C')
group by [type]
它正确地总结了每种“类型”。结果如下:
type total
--------------
Type A 25
Type B 13
但我希望 C 型也包含在结果中(总数量为 0)。
type total
--------------
Type A 25
Type B 13
Type C 0
我怎样才能做到这一点?我正在使用 MS SQL Server 2005。