2

次の表があります。

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 を使用しています。

4

3 に答える 3

0

レポートするタイプのリストを含むテーブルが必要になり、その上で左結合を行います。次のようなもの:

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)

create table #types ( [type] varchar(20) );

insert into #types values ('Type A' );
insert into #types values ('Type B' );
insert into #types values ('Type C' );

select  t.[type], [Total] = IsNull(t.[total], 0)
from    (   select  [type] = IsNull(t.[Type], 'Other')
            ,       [total] = sum(tbl.[qty])
            from    #types                      t
            left
            join    #tbl                        tbl     ON  tbl.[type] = t.type
            group
            by      t.[type]
        ) as t
;

サブクエリは、NULL の合計をゼロに変換するために必要です。

于 2013-05-31T19:45:02.733 に答える
0

また、UNPIVOT 演算子と PIVOT 演算子の両方を適用して結果を取得することもできます。

SELECT type, qty
FROM(
     SELECT COALESCE([Type A], 0) AS [Type A],
            COALESCE([Type B], 0) AS [Type B],
            COALESCE([Type C], 0) AS [Type C]
     FROM (
           SELECT [type], [qty]
           FROM #tbl
           ) x
     PIVOT (
            SUM([qty]) FOR [type] IN([Type A], [Type B], [Type C])
            ) p
     )x
UNPIVOT (
         [qty] FOR [type] IN([Type A], [Type B], [Type C])
         ) u

SQLFiddle のデモ

于 2013-05-31T20:07:04.783 に答える