Gre*_*g B 3 sql-server-2008 t-sql
我有一张桌子,里面放着两种类型的笔记。提货单和交货单。它们是相同的数据结构,因此使用相同的表。
CREATE TABLE Notes (
Id int IDENTITY(1,1) NOT NULL,
Type int NOT NULL,
CustomerId int NOT NULL,
-- etc
)
Run Code Online (Sandbox Code Playgroud)
我正在将数据从旧系统迁移到此表中,并且要求收款和交付票据具有自己的序列号。
我之前已经实现了两个序列表
CREATE TABLE CollectionNoteSequence (
Id int IDENTITY(1,1) NOT NULL,
NoteId int NOT NULL
)
Run Code Online (Sandbox Code Playgroud)
其中该Id
列是收藏笔记的唯一顺序 ID,然后是 NoteId 外键的 to Notes.Id
。
现在是进行最终(真实)数据迁移的时候了,而且这种设置似乎很难使用。
有没有办法可以将两个序列表合并并NoteNo
在 Notes 表中添加一个字段,以便NoteNo
根据Note.Type
? 这是复合键还是什么?
新表可能看起来像
CREATE TABLE Notes (
Id int IDENTITY(1,1) NOT NULL,
NoteNo int NOT NULL,
Type int NOT NULL,
CustomerId int NOT NULL,
-- etc
)
Run Code Online (Sandbox Code Playgroud)
数据看起来像:
Id NoteNo Type CustomerId
1 4000 1 123
2 4001 1 456
3 15123 2 789
4 4002 1 753
5 15124 2 741
Run Code Online (Sandbox Code Playgroud)
我正在使用 MS SQL Server 2008。
您可以partition by
在笔记类型上使用,它允许按组重置计算。例如:
create table OldNotes (
OldNoteRef varchar (20) not null
,OldNoteType varchar (20)
-- Other data goes here
)
go
insert OldNotes (OldNoteRef, OldNoteType) values ('CABC123', 'C')
insert OldNotes (OldNoteRef, OldNoteType) values ('CABC456', 'C')
insert OldNotes (OldNoteRef, OldNoteType) values ('CABC789', 'C')
insert OldNotes (OldNoteRef, OldNoteType) values ('DXYZ001', 'D')
insert OldNotes (OldNoteRef, OldNoteType) values ('DXYZ034', 'D')
insert OldNotes (OldNoteRef, OldNoteType) values ('XZYZ100', 'D')
go
select OldNoteRef
,OldNoteType
,row_number() over (
partition by OldNoteType
order by OldNoteRef
) as NewNoteID
from OldNotes
go
Run Code Online (Sandbox Code Playgroud)
将产生以下结果,这将为您提供音符类型中的序列。
????????????????????????????????????????
? OldNoteRef ? OldNoteType ? NewNoteID ?
????????????????????????????????????????
? CABC123 ? C ? 1 ?
? CABC456 ? C ? 2 ?
? CABC789 ? C ? 3 ?
? DXYZ001 ? D ? 1 ?
? DXYZ034 ? D ? 2 ?
? XZYZ100 ? D ? 3 ?
????????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)
顺便说一句,由http://www.sensefulsolutions.com/2010/10/format-text-as-table.html制作的表格
归档时间: |
|
查看次数: |
3055 次 |
最近记录: |