当字段不存在时求和

时间:2013-05-31 19:24:15

标签: sql sql-server sql-server-2008 tsql sql-server-2005

我有下表:

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

但我希望Type C也包含在结果中(总数量为0)。

type    total
--------------
Type A     25
Type B     13
Type C      0

我怎样才能做到这一点? 我正在使用MS SQL Server 2005。

3 个答案:

答案 0 :(得分:4)

问题是表中没有Type C,因此无法返回。一种方法是创建一个包含所需值的派生表,然后左键加入表:

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 with Demo

答案 1 :(得分: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总和转换为零所必需的。

答案 2 :(得分: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上的演示

相关问题