次の表があります。
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 を使用しています。