![](/img/trans.png)
[英]SQL Server - Compare on multiple columns in differnet rows within same table
[英]Compare multiple rows from the same table in SQL Server 2005
CREATE TABLE #im ( SId int, Reporting_Year_Id int );
GO
INSERT #im (SId, Reporting_Year_Id) VALUES (1,2011)
INSERT #im (SId, Reporting_Year_Id) VALUES (2,2011)
INSERT #im (SId, Reporting_Year_Id) VALUES (3,2011)
GO
CREATE TABLE #im1 ( SID int, PID int, Release int, Legal int, Seq int);
GO
INSERT #im1 (SID, PID, Release, Legal, Seq) VALUES (1,10005,1,18,1) --Trans_Type should be 'A'
INSERT #im1 (SID, PID, Release, Legal, Seq) VALUES (1,10005,1,10,1) --Trans_Type should be 'C'
INSERT #im1 (SID, PID, Release, Legal, Seq) VALUES (2,10005,1,18,1) --Trans_Type should be ' '
INSERT #im1 (SID, PID, Release, Legal, Seq) VALUES (3,10006,1,20,1) --Trans_Type should be 'A'
GO
declare @iCurrentFileId int
set @iCurrentFileId = 2;
WITH current_file as
(
select * from #im1 where SID = @iCurrentFileId
)
, previous_file as
(
select * from #im1 where SID = @iCurrentFileId -1
)
select c.SID, c.PID,c.Legal,c.Release,c.Seq,p.SID,
case when p.SID IS null then 'A'
else 'C' end as 'transaction_type'
from current_file c left outer join previous_file p on p.PID = c.PID and c.Seq = p.Seq
我需要将transaction_Type设置为:
如果前一个SID中不存在除SID以外的所有记录,则为“ A”
如果除SID之外的所有记录均与先前的SID不同,则为'C'
如果除SID以外的所有记录均相同,则为''
怎么做? 任何帮助将非常感激。 谢谢。
一种方法是根据您的业务规则在临时表上执行更新,然后返回结果。 例如,这将满足事务类型A:
declare @im table(previousID int, previousSID int, recentID int, recentSID int, transaction_type varchar(50))
insert into @im(previousID, previousSID, recentID, recentSID, transaction_type) values (1,2,7,9,'')
insert into @im(previousID, previousSID, recentID, recentSID, transaction_type) values (2,2,8,2,'')
insert into @im(previousID, previousSID, recentID, recentSID, transaction_type) values (3,3,9,3,'')
insert into @im(previousID, previousSID, recentID, recentSID, transaction_type) values (4,3,10,3,'')
insert into @im(previousID, previousSID, recentID, recentSID, transaction_type) values (5,4,11,4,'')
insert into @im(previousID, previousSID, recentID, recentSID, transaction_type) values (6,4,12,4,'')
/* 'A' if all records in the most recent SID doesn't exist in the previous SID */
update im
set transaction_type = 'A - 9 is not one of the previous SIDs'
from @im im
where im.recentSID not in (
select distinct previousSID from @im
)
/* add additional updates based on your business rules... */
/* finally return the results */
select * from @im
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.