34,590
社区成员
发帖
与我相关
我的任务
分享
;with cte(BillNo,diff1) as
(
select 20131009001,0
union all select 20131009001,0
union all select 20131009001,27
union all select 20131009001,27
union all select 20131009001,0
union all select 20131009002,0
union all select 20131009002,0
union all select 20131009002,0
union all select 20131009003,0
union all select 20131009003,0
union all select 20131009003,0
union all select 20131009003,0
union all select 20131009003,0
)
--SQL 2005+
SELECT *,[sum]=SUM(diff1) OVER(PARTITION BY BillNo),sum1=SUM(diff1) OVER()
FROM cte
;with cte(BillNo,diff1) as
(
select 20131009001,0
union all select 20131009001,0
union all select 20131009001,27
union all select 20131009001,27
union all select 20131009001,0
union all select 20131009002,0
union all select 20131009002,0
union all select 20131009002,0
union all select 20131009003,0
union all select 20131009003,0
union all select 20131009003,0
union all select 20131009003,0
union all select 20131009003,0
)
select *,[sum]=(select SUM(diff1) from cte b where a.BillNo=b.BillNo)
,[sum1]=(select SUM(diff1) from cte)
from cte a
/*
BillNo diff1 sum sum1
20131009001 0 54 54
20131009001 0 54 54
20131009001 27 54 54
20131009001 27 54 54
20131009001 0 54 54
20131009002 0 0 54
20131009002 0 0 54
20131009002 0 0 54
20131009003 0 0 54
20131009003 0 0 54
20131009003 0 0 54
20131009003 0 0 54
20131009003 0 0 54
*/
create table #tab(BillNo varchar(50),diff1 int)
insert into #tab
select 20131009001,0 union all
select 20131009001,0 union all
select 20131009001,27 union all
select 20131009001,27 union all
select 20131009001,0 union all
select 20131009002,0 union all
select 20131009002,0 union all
select 20131009002,0 union all
select 20131009003,0 union all
select 20131009003,0 union all
select 20131009003,0 union all
select 20131009003,0 union all
select 20131009003,0
select *,
(select SUM(diff1) from #tab b where a.BillNo=b.BillNo
group by BillNo)sum,
(select SUM(diff1) from #tab)sum1
from #tab a
-------------------------------------------
BillNo diff1 sum sum1
-------------------------------------------------- ----------- ----------- -----------
20131009001 0 54 54
20131009001 0 54 54
20131009001 27 54 54
20131009001 27 54 54
20131009001 0 54 54
20131009002 0 0 54
20131009002 0 0 54
20131009002 0 0 54
20131009003 0 0 54
20131009003 0 0 54
20131009003 0 0 54
20131009003 0 0 54
20131009003 0 0 54