关于数据统计的应用

 原表:
销售单号 商品编号
001 1
001 2
001 3
001 4
002 1
003 3
003 4

简单说明:每次销售出去的商品可能相同,可能不同,现在要按商品编号分组统计一下各商品被销售的单号

查询结果如下:
商品编号 销售单号
1 001,002
2 001
3 001,003
4 001,003

 

 

测试数据录入
create table test_2
(销售单号 varchar(225),商品编号 int)

drop table test_2

insert into test_2 values('001',1)

insert into test_2 values('001',2)

insert into test_2 values('001',3)

insert into test_2 values('001',4)

insert into test_2 values('002',1)

insert into test_2 values('003',2)

insert into test_2 values('003',3)

------------------存储过程----------------

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

ALTER PROCEDURE GET_DETIAL as

declare @商品编号 int
declare @销售单号 varchar(50)
declare @销售单号_sum varchar(255)

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[#result]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[#result]
-----------------------创建结果表----------------------------
create table #result (
商品编号 int,
销售单号 varchar(225))


declare cur_商品编号 scroll cursor for select distinct 商品编号 from test_2
open cur_商品编号
fetch first from cur_商品编号 into @商品编号
while (@@fetch_status <> -1)
begin
set @销售单号_sum=''

declare cur_销售单号 scroll cursor
for
select distinct 销售单号 from test_2 where 商品编号=@商品编号

open cur_销售单号
fetch first from cur_销售单号 into @销售单号

while (@@fetch_status <> -1)
begin
if len(@销售单号_sum) = 0
set @销售单号_sum=@销售单号
else
set @销售单号_sum=@销售单号_sum+','+@销售单号
fetch next from cur_销售单号 into @销售单号
end
close cur_销售单号
DEALLOCATE cur_销售单号
insert into #result values(@商品编号,@销售单号_sum)
fetch next from cur_商品编号 into @商品编号
end

close cur_商品编号
DEALLOCATE cur_商品编号

select * from #result


GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO


-----------------------执行
--exec GET_DETIAL

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值