34,837
社区成员




--设表名为a
select a.*,b.[数量] as [同编号总数量]
from a,(select [合同编号],sum([数量]) as [数量] from a group by [合同编号]) b
where a.[合同编号]=b.[合同编号]
if object_id('tb','U') is not null
drop table tb
go
create table tb
(
合同编号 int,
物料 varchar(10),
数量 int
)
go
insert into tb
select 111,'B',1 union all
select 112,'B',2 union all
select 112,'C',1
go
select *,同编号总数量=(select sum(数量) from tb where 合同编号=a.合同编号) from tb a
create table #t(合同编号 int, 物料 varchar(10), 数量 int)
go
insert into #t
select 111, 'B', 1
union all
select 112, 'B', 2
union all
select 112, 'C', 1
select 合同编号, 物料, 数量,SUM(数量)over(partition by 合同编号 ) 同编号总数量 from #t
---------------
合同编号 物料 数量 同编号总数量
111 B 1 1
112 B 2 3
112 C 1 3
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2011-10-11 16:24:40
-- Version:
-- Microsoft SQL Server 2008 R2 (RTM) - 10.50.1617.0 (Intel X86)
-- Apr 22 2011 11:57:00
-- Copyright (c) Microsoft Corporation
-- Enterprise Evaluation Edition on Windows NT 6.1 <X64> (Build 7600: ) (WOW64)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([合同编号] int,[物料] varchar(1),[数量] int)
insert [tb]
select 111,'B',1 union all
select 112,'B',2 union all
select 112,'C',1
--------------开始查询--------------------------
select
a.*,b.num as 同编号总数量
from
tb a,
(select 物料,sum( 数量) as num from tb group by 物料)b
where
a.物料=b.物料
----------------结果----------------------------
/* 合同编号 物料 数量 同编号总数量
----------- ---- ----------- -----------
111 B 1 3
112 B 2 3
112 C 1 1
(3 行受影响)
*/
select
a.*,b.num as 同编号总数量
from
tb a,
(select 物料,sum( 数量) as num from tb group by 物料)b
where
a.物料=b.物料
create table tb(合同编号 int,物料 nvarchar(10),数量 int)
insert into tb select 111,'B',1
insert into tb select 112,'B',2
insert into tb select 112,'C',1
go
select *,(select sum(数量) from tb where 合同编号=a.合同编号) as 同编号总数量 from tb a
/*
合同编号 物料 数量 同编号总数量
----------- ---------- ----------- -----------
111 B 1 1
112 B 2 3
112 C 1 3
(3 行受影响)
*/
go
drop table tb
select *,
同编号总数量=(select sum(数量) from 表A where 合同编号=a.合同编号)
from 表A a
selet *,(select sum(数量) from tb where 合同编号=a.合同编号) as 同编号总数量 from tb a