+ -
当前位置:首页 → 问答吧 → SQL查询的一个问题?

SQL查询的一个问题?

时间:2011-12-03

来源:互联网

格式如下:

区域 厂家
龙泉 诺西
高新 华为
高新 诺西
高新 诺西
高新 诺西

问题:想查出每个区域中厂家为华为和厂家为诺西的计数,求语句,谢谢!结果应该是


区域 诺西 华为
龙泉 1 0  
高新 3 1

作者: sxssg   发布时间: 2011-12-03

SQL code
select 区域,诺西=sum(case when 厂家='诺西' then 1 else 0 end),
            华为=sum(case when 厂家='华为' then 1 else 0 end)
from tb group by 区域

作者: ssp2009   发布时间: 2011-12-03

SQL code
select
  区域,
  sum(case 厂家 when '诺西' then 1 else 0 end) as 诺西,
  sum(case 厂家 when '华为' then 1 else 0 end) as 华为
from
   tb
group by
   区域

作者: fredrickhu   发布时间: 2011-12-03

SQL code

select 区域,sum(case when 厂家='华为' then 1 else 0 end) [华为],
       sum(case when 厂家='诺西' then 1 else 0 end) [诺西]
from tb
group by 区域

作者: AcHerat   发布时间: 2011-12-03

引用 1 楼 ssp2009 的回复:

SQL code
select 区域,诺西=sum(case when 厂家='诺西' then 1 else 0 end),
华为=sum(case when 厂家='华为' then 1 else 0 end)
from tb group by 区域

作者: smilysoft   发布时间: 2011-12-03

SQL code

if object_id('tb','U') is not null
   drop table tb
go
create table tb
(
 区域 varchar(10),
 厂家 varchar(10)
)
go
insert into tb
select '龙泉','诺西' union all
select '高新','华为' union all
select '高新','诺西' union all
select '高新','诺西' union all
select '高新','诺西'
go
declare @str varchar(max)
select @str=isnull(@str+',','')+'['+厂家+']=sum(case when 厂家='''+厂家+''' then 1 else 0 end)' from (select distinct 厂家 from tb) t1
exec('select 区域,'+@str+' from tb group by 区域')
go
/*
区域         华为          诺西
---------- ----------- -----------
高新         1           3
龙泉         0           1

(2 行受影响)

*/

作者: pengxuan   发布时间: 2011-12-03