请教SQL查询问题,请各位帮忙

HDJ2013 2006-05-16 04:26:00
表一
单号 编码 数量
1 b 10
2 a 20
3 a 15
4 b 12
5 b 14

现求:
作表一的一个视图
字段与其一样,只加一个字段 为 余额
余额的值为同编码的不比本单单号大的所有单据数量的和
求出来的表应为
表二
单号 编码 数量 余额
1 b 10 10
2 a 20 20
3 a 15 35
4 b 12 22
5 b 14 36
小弟,实在想不出来了,请各位高手帮忙


...全文
141 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
上面的sql需在sql2005下执行, sql2000不支持分析函数Row_Number() over(...)
  • 打赏
  • 举报
回复
create table Bill(
BillId int identity,
Code varchar(2),
Qty int
constraint PK_Bill primary key (BillId))
go

insert into Bill(Code, Qty)
select 'b', 10
union all
select 'a', 20
union all
select 'a', 15
union all
select 'b', 12
union all
select 'b', 14
go

create view v_Bill as
select BillId, Code, Qty, (Row_Number() over(partition by Code order by BillId)) SortNo
from Bill
go

select A.BillId, A.Code, A.Qty, A.Qty + IsNull(B.Qty, 0) Total
from V_Bill A left outer join V_Bill B
on A.Code = B.Code
and A.SortNo = B.SortNo + 1
lxzm1001 2006-05-16
  • 打赏
  • 举报
回复
create table tb(单号 int,编码 varchar(10),数量 int)
insert tb select 1,'b',10
union all select 2,'a',20
union all select 3,'a',15
union all select 4,'b',12
union all select 5,'b',14
select *,(select sum(数量) from tb where 单号<=t.单号 and 编码=t.编码)as 余额 from tb t
yangys 2006-05-16
  • 打赏
  • 举报
回复
create table tb
(
单号 int,
编码 char(1),
数量 int
)

go
insert tb
select 1,'b',10
union all
select 2,'a',20
union all
select 3,'a',15
union all
select 4,'b',12
union all
select 5,'b',14



select *,余额=(select sum(数量) from tb where 单号<=a.单号 and 编码=a.编码)
from tb a



单号 编码 数量 余额
1 b 10 10
2 a 20 20
3 a 15 35
4 b 12 22
5 b 14 36
paoluo 2006-05-16
  • 打赏
  • 举报
回复


--建立測試環境
Create Table 表一
(单号 Int,
编码 Varchar(10),
数量 Int)
--插入數據
Insert 表一 Select 1, 'b', 10
Union All Select 2, 'a', 20
Union All Select 3, 'a', 15
Union All Select 4, 'b', 12
Union All Select 5, 'b', 14
GO
--建立視圖
Create View List As
Select
*,
(Select SUM(数量) From 表一 Where 单号<=A.单号 And 编码=A.编码) As 余额
From 表一 A
GO
--測試
Select * From List
GO
--刪除測試環境
Drop Table 表一
Drop View List
--結果
/*
单号 编码 数量 余额
1 b 10 10
2 a 20 20
3 a 15 35
4 b 12 22
5 b 14 36
*/
paoluo 2006-05-16
  • 打赏
  • 举报
回复
看錯,改

Select
*,
(Select SUM(数量) From 表一 Where 单号<=A.单号 And 编码=A.编码) As 余额
From 表一 A
wangdehao 2006-05-16
  • 打赏
  • 举报
回复
select a.*,余额=(select sum(数量) from 表一 where 编码=a.编码 and 单号<=a.单号)
from 表一 a
itblog 2006-05-16
  • 打赏
  • 举报
回复
select a.*,余额=(select sum(数量) from 表 where 编码=a.编码 and 单号<=a.单号) from 表 a
paoluo 2006-05-16
  • 打赏
  • 举报
回复
Select
*,
(Select SUM(数量) From 表一 Where 单号<=A.单号) As 余额
From 表一 A

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧