【问题标题】:Need helping adjusting SQL query involving table joins需要帮助调整涉及表连接的 SQL 查询
【发布时间】:2015-07-31 15:35:20
【问题描述】:

我有两张桌子:PermanentTableTemporaryTable

TemporaryTable中有7列:

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

所有这些列也在PermanentTable 中,如果IdTemporaryTable 中的一个匹配,则之前已填写。

我有一个查询,它返回 TemporaryTable 中的 ID,显示“Y”的列是 PermanentTable 中匹配的 ID,如果不匹配,则显示“N”。如果匹配,CreditInvoiceDateCreditInvoiceNumberCreditInvoiceAmountCreditDeniedDateCreditDeniedReasonIdCreditDeniedNotes 将填充数据(但不是全部 6 个)。如果它们匹配,还将填充名为 AuthNumber 的列。我的查询返回这些。

查询

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

结果

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

我想调整这个查询,这样我就可以去掉最后的 Matched 列,而是有 2 个 Id 列。一个包含TemporaryTable 中与PermanentTable 匹配的ID,另一个包含不匹配的ID。如果 Id 不匹配,则不会填写其他字段,因此无需检查。

如果您有任何问题,请告诉我。谢谢!

【问题讨论】:

  • 我很好奇,这与您的其他question 有何不同?
  • 因为我试图将 Id 列分为 Id Matched 和 Not Matched 并且只显示匹配时生成的其他列

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    以下查询应该对您有所帮助:

    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
    

    【讨论】:

    • 正是我想要的!不过我不得不做一些细微的调整,所以我会进行编辑
    猜你喜欢
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2014-08-03
    • 1970-01-01
    • 1970-01-01
    • 2011-09-19
    • 1970-01-01
    相关资源
    最近更新 更多