日期:2014-05-17 浏览次数:20479 次
--创建数据开始
if(object_id('a') is not null) drop table a
go
create table a
(
[仓库] int,
[产品编码] varchar(20),
[数量] int
)
go
insert into a
select 1,'001',10 union all
select 2,'001',3 union all
select 3,'001',13 union all
select 1,'002',10 union all
select 2,'002',33 union all
select 3,'002',22
go
--创建数据结束
--语句
select case grouping([产品编码])when 1 then '合计' else [产品编码] end as [产品编码],sum([数量]) as [汇总数量]
from a
group by [产品编码] with rollup
/*
产品编码 汇总数量
-------------------- -----------
001 26
002 65
合计 91
(3 行受影响)
*/
SELECT 产品编码 ,
SUM(数量) 数量
FROM TB
GROUP BY 产品编码
if(object_id('a') is not null) drop table a
go
create table a
(
[仓库] int,
[产品编码] varchar(20),
[数量] int
)
go
insert into a
select 1,'001',10 union all
select 2,'001',3 union all
select 3,'001',13 union all
select 1,'002',10 union all
select 2,'002',33 union all
select 3,'002',22
go
SELECT
产品编码,
(SELECT SUM(数量) FROM a WHERE 产品编码 = d.产品编码) 数量
FROM a d
GROUP BY 产品编码
---测试结果:
产品编码 数量
-------------------- -----------
001 26
002 65
(2 行受影响)