现在有图1的表
,
对diff1列求两种和,加在表后面,得到图2的样子
,
求数据库语句怎么写数据库sum求和增加列
,
对diff1列求两种和,加在表后面,得到图2的样子
,
求数据库语句怎么写数据库sum求和增加列
解决方案 »
- 入门题 获取电信号码段 like 优化
- 求助 sql 多表查询
- 一个客户表,一个活动记录表,查询客户表信息显示 活动表的 活动记录 未联系天数
- 简单查询,急!!!
- 十万火急!大家帮帮忙,几天了!
- TDatabase 中的 Isolation 属性中,tiDirtyRead 和 tiReadCommitted 怎么使用?是不是就是数据库中的锁机制?
- 两个表的数据结构一模一样,怎么比较两个表的数据的差异?
- 一条sql语句,请看看对不对,如果执行的话,是全部数据的总和吗?
- 如何查询还有半角字符的数据。
- 请问一个sql server的问题
- ~~~~~~~~~行转列问题,马上给分!~~~~~~~~~~~
- 文本数据入库sql
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
;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
*/
(
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
(
select 1 as col,timestr,val
from myTable2
)
SELECT timestr,val,
SUM(val) OVER(PARTITION BY timestr
ORDER BY timestr) AS [sum],
sum(val) over(partition by col
order by timestr) as sum1
FROM t