需要帮助调整涉及表连接的SQL查询

时间:2015-07-31 15:35:20

标签: sql sql-server sql-server-2008 join

我有两个表:PermanentTableTemporaryTable

TemporaryTable中有7列:

Id, CreditInvoiceDate, CreditInvoiceNumber, CreditInvoiceAmount, 
CreditDeniedDate, CreditDeniedReasonId, CreditDeniedNotes. 

所有这些列也位于PermanentTable中,如果IdTemporaryTable中的TemporaryTable匹配,则之前已填写。

我有一个返回PermanentTable中的ID的查询,显示'Y'的列是CreditInvoiceDate中匹配的ID,如果不匹配则是'N'。如果匹配,则CreditInvoiceNumberCreditInvoiceAmountCreditDeniedDateCreditDeniedReasonIdCreditDeniedNotesAuthNumber将被填写数据(但不是全部6)。如果匹配,也会填写名为Select t.Id, p.AuthNumber, p.CreditInvoiceDate, p.CreditInvoiceNumber, p.CreditInvoiceAmount, p.CreditDeniedDate, p.CreditDeniedReasonId, p.CreditDeniedNotes, case when p.Id is not null then 'Y' else 'N' end as Matched from TemporaryCsvUpload t left join PermanentTable p on p.Id = t.Id 的列。我的查询返回了那些。

查询

TemporaryTable

结果

enter image description here

这是我已经达到的目的,但这是我要去的地方:

我想调整此查询,以便我可以删除最后的匹配列,而是有2个Id列。一个包含PermanentTable中与SELECT A.* FROM A INNER JOIN ( SELECT ID,MAX(DateTimePerformed) AS 'MaxDateTimePerformed' FROM A GROUP BY ID ) AS B ON A.ID=B.ID AND A.DateTimePerformed=B.MaxDateTimePerformed Order by A.ID ASC 匹配的ID,另一个包含未添加的ID。如果Ids不匹配,那么其他任何字段都不会填写,因此无需检查。

如果您有任何疑问,请与我们联系。谢谢!

2 个答案:

答案 0 :(得分:3)

以下内容应与其他答案一样有效,并且更容易阅读:

Select  p.Id as tempMatchedId, 
        case when p.Id is null then t.Id end as tempUnmatchedId, 
        p.AuthNumber,
        p.CreditInvoiceDate, 
        p.CreditInvoiceNumber,
        p.CreditInvoiceAmount, 
        p.CreditDeniedDate,
        p.CreditDeniedReasonId, 
        p.CreditDeniedNotes
from TemporaryCsvUpload t 
left join PermanentTable p 
       on p.Id = t.Id

答案 1 :(得分:0)

下面的查询可以帮助您:

Select  case when p.Id is not null then t.Id else null end as tempMatchedId, 
case when p.Id is null then t.Id else null end as tempUnmatchedId, 
case when p.Id is not null then p.AuthNumber else null end as AuthNumber,
case when p.Id is not null then p.CreditInvoiceDate else null end as CreditInvoiceDate, 
case when p.Id is not null then p.CreditInvoiceNumber else null end as CreditInvoiceNumber,
case when p.Id is not null then p.CreditInvoiceAmount else null end as CreditInvoiceAmount, 
case when p.Id is not null then p.CreditDeniedDate else null end as CreditDeniedDate,
case when p.Id is not null then p.CreditDeniedReasonId else null end as CreditDeniedReasonId, 
case when p.Id is not null then p.CreditDeniedNotes else null end as CreditDeniedNotes
from TemporaryCsvUpload t 
left join PermanentTable p 
on p.Id = t.Id