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

4

问题是你没有Type C在桌子上,所以没有什么可以返回的。一种方法是创建一个派生表,其中包含您想要包含的所有值,然后 LEFT JOIN 您的表:

select d.type,
  sum(coalesce(t.qty, 0)) Total
from
(
  select 'Type A' type union all
  select 'Type B' type union all
  select 'Type C' type 
) d
left join tbl t
  on d.type = t.type
group by d.type;

请参阅带有演示的 SQL Fiddle

于 2013-05-31T19:27:32.463 回答
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 回答