我想通过第2个表的值来链接2个表。
我有2张桌子。 case_activity(主记录表)和case_activity_changes(日志表)。这两个表是通过ActivityId链接的。
我的第一张桌子看起来像这样
SELECT activityid, caseId, description FROM dbo.case_activity WHERE CaseId = 35057152
activityid caseId description
----------- ----------- --------------------------------------------------
229098 35057152 Receive data correction request from participant
229099 35057152 Verify proof of change, if applicable
229100 35057152 Update Data
229101 35057152 Review / Update pension check address, if app
229102 35057152 Review/Update pension state tax elections, if app
229103 35057152 Technical Review
229104 35057152 Send to print
229105 35057152 Send data change to trustee, if app
229106 35057152 First Call Attempt
229107 35057152 Send data change to NQ pension payer, if app
和第二个
SELECT * FROM dbo.case_activity_changes WHERE ActivityId = 229189
ActivityId TransactionId fieldname OldValue
----------- ------------- -------------------------------------------------- ----------------------------
229189 32710860 ** INSERTED ** NULL
229189 32710861 TransactionId 32710860
229189 32710861 ViewByAssigned NULL
229189 32710862 ** DELETED ** NULL
229189 32710862 ActivityId 229189
229189 32710862 AssignedDate Jan 16 2020 6:47AM
229189 32710862 AssignedUserId 51809
229189 32710862 BeginDate NULL
229189 32710862 CaseId 35057152
229189 32710862 ChangedUserId 51809
229189 32710862 CompletedDate NULL
229189 32710862 CompletedUserId NULL
229189 32710862 CreatedDate Jan 16 2020 6:47AM
229189 32710862 CreatedUserId 51809
229189 32710862 Description DO
229189 32710862 DueDate NULL
229189 32710862 EmailSentTo NULL
229189 32710862 NoteText NULL
229189 32710862 SequenceOrder 40
229189 32710862 Status 1
229189 32710862 SubtypeId 341
229189 32710862 TransactionId 32710861
229189 32710862 ViewedByAssigned Jan 16 2020 6:47AM
我的结果应该看起来像这样
activityid caseId description action
----------- ----------- -------------------------------------------------------------
229098 35057152 Receive data correction request from participant
229099 35057152 Verify proof of change, if applicable
229100 35057152 Update Data
229101 35057152 Review / Update pension check address, if app
229102 35057152 Review/Update pension state tax elections, if app
229103 35057152 Technical Review
229104 35057152 Send to print
229105 35057152 Send data change to trustee, if app
229106 35057152 First Call Attempt
229107 35057152 Send data change to NQ pension payer, if app
229189 35057152 DO DELETED
请注意,最后一条记录activityid = 229189在case_activity中不再存在,但是有一个登录case_activity_changes,指示其已删除,描述值为“ DO”,caseId = 35057152
您无需为此使用join
。对于已删除的交易,请使用union
。
select activityid, caseId, description, '' as Action
from dbo.case_activity where CaseId = 35057152
union all
select ActivityId, 35057152, 'Do', 'Deleted'
from bo.case_activity_changes where ActivityId not in
(select activityid from dbo.case_activity where CaseId = 35057152)