统计编号前面两位相同的金额合计前面两位 11代表A小区,12代表B小区,13代表C小区
编号 日期 类型 金额
12047 2011-10-9 0:00 收视 26
12246 2011-10-9 0:00 安装 78
11161 2011-10-9 0:00 收视 26
11166 2011-10-9 0:00 收视 156
11238 2011-10-9 0:00 安装 26结果就像;
小区 收视 安装
A小区 182 26
B小区 26 78
编号 日期 类型 金额
12047 2011-10-9 0:00 收视 26
12246 2011-10-9 0:00 安装 78
11161 2011-10-9 0:00 收视 26
11166 2011-10-9 0:00 收视 156
11238 2011-10-9 0:00 安装 26结果就像;
小区 收视 安装
A小区 182 26
B小区 26 78
case left(编号,2) when '11' then 'A小区' when '12' then 'B小区' else 'C小区' end as 区,
sum(case 类型 when '收视' then 金额 else 0 end) as '收视' ,
sum(case 类型 when '安装' then 金额 else 0 end) as '安装'
from
tb
group by
left(编号,2)
區 金额
A小区 208
B小区 52
C小区 338
*/select
case left(编号,2) when '11' then 'A小区' when '12' then 'B小区' else 'C小区' end as 区,
sum(金额) as 金额
from
tb
group by
left(编号,2)
go
--> -->
if not object_id(N'B') is null
drop table B
Go
Create table B([编号] int,[日期] Datetime,[类型] nvarchar(2),[金额] int)
Insert B
select 12047,'2011-10-9',N'收视',26 union all
select 12246,'2011-10-9',N'安装',78 union all
select 11161,'2011-10-9',N'收视',26 union all
select 11166,'2011-10-9',N'收视',156 union all
select 11238,'2011-10-9',N'安装',26
Go
Select
case left(编号,2) when '11' then N'A小区' when '12' then N'B小区' else N'C小区' END AS N'區',
sum(CASE [类型] WHEN N'收视' THEN [金额] ELSE 0 END) as N'收视',
sum(CASE [类型] WHEN N'安装' THEN [金额] ELSE 0 END) as N'安装'from B
GROUP BY left(编号,2)/*
區 收视 安装
A小区 182 26
B小区 26 78
*/
--> 测试数据: [tb]
if object_id('[tb]') is not null drop table [tb]
create table [tb] (编号 int,日期 datetime,类型 varchar(4),金额 int)
insert into [tb]
select 12047,'2011-10-9 0:00','收视',26 union all
select 12246,'2011-10-9 0:00','安装',78 union all
select 11161,'2011-10-9 0:00','收视',26 union all
select 11166,'2011-10-9 0:00','收视',156 union all
select 11238,'2011-10-9 0:00','安装',26--开始查询
select 小区=case
when LEFT(编号,2)=11 then 'A小区'
when LEFT(编号,2)=12 then 'B小区'
when LEFT(编号,2)=13 then 'c小区'
end,
收视=sum(case when 类型='收视' then 金额 else 0 end),
安装=sum(case when 类型='安装' then 金额 else 0 end)
from [tb]
group by LEFT(编号,2)--结束查询
drop table [tb]/*
小区 收视 安装
----- ----------- -----------
A小区 182 26
B小区 26 78(2 行受影响)
select case when left(ltrim(编号),2)='11' then 'A小区'
when left(ltrim(编号),2)='12' then 'B小区'
when left(ltrim(编号),2)='13' then 'C小区'
end as 小区,
case when 类型='收视' then 金额 else 0 end as 收视,
case when 类型='安装' then 金额 else 0 end as 安装
from tb
)t group by 小区
from tb a
group by SUBSTRING(编号,1,2)