34,590
社区成员
发帖
与我相关
我的任务
分享
我想依下表統計出 pcategory 有哪些 cno 買?各個 pcategory 購買的 quantity 有多少?
cno |
quantity |
pcategory |
0260000266565 |
2 |
1 |
0260000266565 |
1 |
3 |
0260000660967 |
1 |
1 |
0260000663036 |
1 |
3 |
0260000664378 |
10 |
5 |
0260000664378 |
1 |
4 |
0260000664590 |
1 |
1 |
0260000664590 |
2 |
4 |
0260000664767 |
1 |
1 |
0260000664767 |
4 |
6 |
--建立测试表
select * into 测试表 from (
select cno = 0260000266565,quantity=2,pcategory=1
union all
select cno = 0260000266565,quantity=1,pcategory=3
union all
select cno = 0260000660967,quantity=1,pcategory=1
union all
select cno = 0260000663036,quantity=1,pcategory=3
union all
select cno = 0260000664378,quantity=10,pcategory=5
union all
select cno = 0260000664378,quantity=1,pcategory=4
union all
select cno = 0260000664590,quantity=1,pcategory=1
union all
select cno = 0260000664590,quantity=2,pcategory=4
union all
select cno = 0260000664767,quantity=1,pcategory=1
union all
select cno = 0260000664767,quantity=4,pcategory=6
)T
--开始实现统计
--利用动态sql创建临时表
if object_id('tempdb..##全局临时表_1') is not null drop table ##T_1
declare @row int = (select max(pcategory) from 测试表) --需要循环创建的列数,用pcategory最大值作为最大列数
declare @拼接sql_1 nvarchar(max)
--创建表
set @拼接sql_1 = 'create table ##全局临时表_1 (cno bigint,Total int'
declare @i nvarchar(50) = 1
WHILE @i<=@row
BEGIN
set @拼接sql_1 = @拼接sql_1+',Item_'+@i+' int'
set @i = @i+1
END
exec (@拼接sql_1+')') --创建临时表
--向临时表中写入统计数据
declare 游标_1 cursor Scroll --声明游标循环
for
select cno,quantity=sum(quantity),T1.Total,pcategory from 测试表 as a1
cross apply(select Total = sum(quantity) from 测试表 as b1 where b1.cno = a1.cno)T1
group by cno,pcategory,T1.Total --循环处理的数据
open 游标_1 --打开游标
declare @cno nvarchar(50),@quantity nvarchar(50),@Total nvarchar(50),@pcategory nvarchar(50)
fetch first from 游标_1 into @cno,@quantity,@Total,@pcategory --第一次循环,同时声明所有需要处理的字段变量
while @@fetch_status=0 --游标读取下一条是否成功
begin --成功则进入循环
--使用merge更新或写入数据
declare @拼接sql_2 nvarchar(max) = 'merge into ##全局临时表_1 as T1
using (select cno = '''+@cno+''',quantity = '''+@quantity+''',Total = '''+@Total+''',pcategory = '''+@pcategory+''') as T2 on T1.cno = T2.cno
when matched then update set T1.Total = T2.Total,T1.Item_'+@pcategory+' = T2.quantity --满足T1.cno=T2.cno时,更新T1
when not matched then insert (cno,Total,Item_'+@pcategory+') values(T2.cno,T2.Total,T2.quantity) --不满足T1.cno=T2.ID时,则插入T2行
;'
exec (@拼接sql_2)
fetch Next from 游标_1 into @cno,@quantity,@Total,@pcategory --下一次循环,同时声明所有需要处理的字段变量
end
close 游标_1 --关闭循环
deallocate 游标_1 --关闭游标
--查询统计数据
select * from ##全局临时表_1
--查完删除全局临时表
drop table ##全局临时表_1
希望能以表格形式给出期望的查询结果,否则你描述的指向太多可能,不知道你要哪种