物品表:
IF OBJECT_ID('tempdb..#tmpItemDetail') IS NOT NULL DROP TABLE #tmpItemDetail
create table #tmpItemDetail
(
[Stock_Type] char(2) NOT NULL, --主键(物品类型)
[Stock_Group] smallint NOT NULL,--主键(物品分组)
[Stock No] int NOT NULL, --主键(物品编号)
[Dname] varchar(50) not null,(物品小类)
[Detail name] varchar(50) not null, (证书名称)
)
insert into #tmpItemDetail values('A',1,0,'无','0'),
insert into #tmpItemDetail values('A',1,1,'封装类','0')
insert into #tmpItemDetail values('A',2,0,'封装类','Test4')
insert into #tmpItemDetail values('A',2,1,'装订类','Test1')
历史表:
IF OBJECT_ID('tempdb..#tmpItemDetailHistory') IS NOT NULL DROP TABLE #tmpItemDetailHistory
create table #tmpItemDetailHistory
(
[Stock_Type] char(2) NOT NULL, --主键(物品类型)
[Stock_Group] smallint NOT NULL,--主键(物品分组)
[Stock No] int NOT NULL, --主键(物品编号)
[Date] datetime NOT NULL,(修改日期)
[User ID] char(10) not null,(用户ID)
[Update Seq] int NOT NULL,(随机标记自动增长)
[Dname] varchar(50) not null,(物品小类)
[Detail name] varchar(50) not null, (证书名称)
[Tran Code] smallint NOT NULL(修改标记,0修改前,1修改后)
)
insert into #tmpItemDetailHistory values('A',1,0,'2012-1-2',1,1,'装订类','Test1',0),
insert into #tmpItemDetailHistory values('A',1,0,'2012-1-2',1,2,'无','Test1',1),
insert into #tmpItemDetailHistory values('A',1,0,'2012-1-3',1,3,'无','Test1',0),
insert into #tmpItemDetailHistory values('A',1,0,'2012-1-3',1,5,'无','0',1),
insert into #tmpItemDetailHistory values('A',1,1,'2012-1-2',1,6,'密封类','Test1',0),
insert into #tmpItemDetailHistory values('A',1,1,'2012-1-2',1,8,'封装类','0',1),
insert into #tmpItemDetailHistory values('A',2,0,'2012-1-5',1,9,'无','0',0),
insert into #tmpItemDetailHistory values('A',2,0,'2012-1-5',1,11,'无','Test1',1),
insert into #tmpItemDetailHistory values('A',2,0,'2012-1-6',1,13,'无','Test1',0),
insert into #tmpItemDetailHistory values('A',2,0,'2012-1-6',1,15,'封装类','Test3',1),
insert into #tmpItemDetailHistory values('A',2,0,'2012-1-7',1,18,'封装类','Test3',0),
insert into #tmpItemDetailHistory values('A',2,0,'2012-1-7',1,20,'封装类','Test4',1),
说明:物品三个主键决定该物品名称(三个主键并接在一起就是该物品的名称)修改可能是多次,但可能不是针对”证书名称“也可能是修改别的数据。如“证书名称”修改多次则只取最后一次的更改数据数据。[Update Seq]字段依次增大,也就是说[Tran Code]修改前(0)比修改后(1)小
请帮忙抽出有更变“证书名称”一栏的详细数据(表#tmpItemDetail 所有字段)
请多多帮忙,谢谢各位。
Tran Code和UpdateSeq这两个段字是多余的,你的tmpItemDetailHistory应该只记录每次修改的这条数据就行了,因为修改后的数据永远是你tmpItemDetail表的这行数据
抽取有更变证书名称的数据,思路:tmpItemDetailHistory有当前物品的记录(三个主键相同)同时“证书名称不一致”
select A.* from #tmpItemDetail A left join ( select distinct A.stock_type, A.Stock_group,A.[stock No] from #tmpItemDetailHistory A left join #tmpItemDetail B on A.stock_type=B.Stock_type and A.Stock_group=B.Stock_group and A.[stock No]=B.[Stock no] and A.[detail name]<>B.[detail name]--获取变更过证书的物品 ) B on A.stock_type=B.Stock_type and A.Stock_group=B.Stock_group and A.[stock No]=B.[Stock no] where B.stock_type is not null
这个用外连接试试