读书人

简单的查询

发布时间: 2012-01-13 22:43:29 作者: rapoo

简单的查询 求助
月份 区域 销售总价
------ ------ -------------------------
03月 宝山区 620000
03月 宝山区 750000
03月 宝山区 900000
03月 宝山区 1100000
03月 奉贤区 861000
03月 奉贤区 1090000
03月 虹口区 1000000
03月 虹口区 1100000
03月 嘉定区 430000
03月 嘉定区 1090000
03月 嘉定区 1200000
03月 金山区 750000
03月 金山区 1090000
03月 金山区 5200000
03月 闵行区 430000
03月 闵行区 620000


03月 闵行区 1090000
03月 闵行区 1100000
希望出来结果
月份 区域 销售总价
------ ------ -------------------------
03月 宝山区 620000+750000+900000+1100000

下面类似。


[解决办法]
select 月份,区域,sum(销售总价) as 销售总价 from table group by 月份,区域
[解决办法]
if object_id( 'temp ')> 0 drop table temp
create table temp([月份] varchar(20),[区域] varchar(20),[销售总价] int)
insert into temp
select '03月 ', '宝山区 ', 620000
union all
select '03月 ', '宝山区 ', 750000
union all
select '03月 ', '宝山区 ', 900000
union all
select '03月 ', '宝山区 ', 1100000
union all
select '03月 ', '奉贤区 ', 861000
union all
select '03月 ', '奉贤区 ', 1090000
union all
select '03月 ', '虹口区 ', 1000000
union all
select '03月 ', '虹口区 ', 1100000
union all
select '03月 ', '嘉定区 ', 430000
union all
select '03月 ', '嘉定区 ', 1090000
union all
select '03月 ', '嘉定区 ', 1200000
union all
select '03月 ', '金山区 ', 750000
union all
select '03月 ', '金山区 ', 1090000
union all
select '03月 ', '金山区 ', 5200000
union all
select '03月 ', '闵行区 ', 430000
union all
select '03月 ', '闵行区 ', 620000
union all
select '03月 ', '闵行区 ', 1090000
union all
select '03月 ', '闵行区 ', 1100000

go

alter function fun_total(@str varchar(20))
returns varchar(100)
begin
declare @e varchar(8000)
set @e= ' '
select @e=@e+ '+ '+convert(varchar(20),[销售总价]) from temp where [区域]=@str
set @e=stuff(@e,1,1, ' ')
return @e
end

go

select [月份],[区域],dbo.fun_total([区域]) as [销售总价] from temp group by [月份],[区域]


drop table temp
/*
月份 区域 销售总价
--------------------------------------
03月宝山区620000+750000+900000+1100000
03月闵行区430000+620000+1090000+1100000
03月奉区区861000+1090000
03月金山区750000+1090000+5200000
03月虹口区1000000+1100000
03月嘉定区430000+1090000+1200000
*/
[解决办法]
select 月份,区域,sum(销售总价) from 表
where 区域 in (select distinct 区域 from 表)


group by 月份,区域

读书人网 >SQL Server

热点推荐