我想在SubQuery中转换内部联接查询

时间:2019-07-18 14:26:51

标签: sql-server

我在查询中使用内部联接,但我希望使用子查询代替联接

select [Document No_] as DocumentNo,
       ledger.[Posting Date] as Date,
       [Sales (LCY)] as Amount,
       header.[Customer Reference] as PONo
from   [Uneek Clothing Company Ltd$Cust_ Ledger Entry] ledger 
  inner join [Uneek Clothing Company Ltd$Sales Invoice Header] header on ledger.[Entry No_]=header.[Cust_ Ledger Entry No_]
where  [Customer No_] = 'DRC01' 
and    [Document Type]=2 
and    [Sales (LCY)]!=0 
and    ledger.[Posting Date] between '01/01/2019' and '12/31/2019' 
order by [Sales (LCY)] asc offset 0 ROWS FETCH NEXT 20 ROWS ONLY

[Entry No_]是[Uneek Clothing Company Ltd $ Sales发票标题]中的外键,名称为[Cust_ Ledger Entry No _]

1 个答案:

答案 0 :(得分:0)

如果您真的要删除联接并改为使用子查询,
它看起来像这样。

由于您没有为所有列使用表别名,因此我不得不假定子查询中表的其他列在其他任何地方都没有使用。如果不是这种情况,那就行不通了

它也仅在子查询返回的行不超过1行时才起作用,否则子查询根本无法使用

select [Document No_] as DocumentNo,
       ledger.[Posting Date] as Date,
       [Sales (LCY)] as Amount,
       ( select header.[Customer Reference] 
         from  [Uneek Clothing Company Ltd$Sales Invoice Header] header 
         where ledger.[Entry No_] = header.[Cust_ Ledger Entry No_]
       ) as PONo
from   [Uneek Clothing Company Ltd$Cust_ Ledger Entry] ledger 
where  [Customer No_] = 'DRC01' 
and    [Document Type]=2 
and    [Sales (LCY)]!=0 
and    ledger.[Posting Date] between '01/01/2019' and '12/31/2019' 
order by [Sales (LCY)] asc 
offset 0 ROWS FETCH NEXT 20 ROWS ONLY