简体   繁体   English

SQL在子查询中返回空单元格

[英]Sql return empty cell in subquery

I have two tables: 我有两个表:

transfers
| No_ | PostingDate | Code |

comments
| No_ | comment |

One transfer can have many comments. 一次转移可以有很多评论。

I need to create a query that returns all transfers and the top 1 comment from its comments or an empty comment if it has no comments. 我需要创建一个查询,该查询返回所有转账以及其注释中的前1条注释,如果没有注释,则为空注释。

SELECT 
    th.[No_], 
    th.[Posting Date] as 'PostingDate',
    th.[Transfer-to Code] as 'Transfer_To', 
    icl.Comment
FROM 
    dbo.[company$Transfer Header] as th,
    dbo.[company$Inventory Comment Line] as icl
where 
    th.No_=icl.No_

I have this but it only returns transfers with comments. 我有这个,但它只返回带有注释的传输。

How can I return all transfers and if a transfer does not have a comment then an empty comment is returned. 我该如何退回所有转账,如果转账没有评论,则返回空评论。

Use a LEFT JOIN along with COALESCE to replace the missing NULL values with an empty comment: LEFT JOINCOALESCE一起用空注释替换缺少的NULL值:

SELECT th.[No_], th.[Posting Date] as 'PostingDate',
       th.[Transfer-to Code] as 'Transfer_To',
       COALESCE(icl.Comment, '')
FROM
    dbo.[company$Transfer Header] AS th
LEFT JOIN
    dbo.[company$Inventory Comment Line] AS icl
    ON th.No_ = icl.No_

I might be inclined to use outer apply for this: 我可能倾向于使用outer apply

SELECT th.[No_], th.[Posting Date] as PostingDate,
       th.[Transfer-to Code] as Transfer_To,
       COALESCE(icl.Comment, '') as Comment
FROM dbo.[company$Transfer Header] as th OUTER APPLY
     (SELECT TOP 1 icl.*
      FROM dbo.[company$Inventory Comment Line] icl
      WHERE th.No_ = icl.No_
     ) icl;

This assumes that you want one comment and that when there are no comments, you want an empty string. 这假定您要一个注释,并且当没有注释时,您需要一个空字符串。

Notes: 笔记:

  • The subquery should have an ORDER BY clause, but it is unclear how you want to choose the one comment. 子查询应具有ORDER BY子句,但尚不清楚如何选择一个注释。
  • Do not use implicit JOIN syntax. 不要使用隐式JOIN语法。
  • Only use single quotes for string and date constants. 仅对字符串和日期常量使用单引号。 Although allowed when defining a column alias, they are not allowed when using it, so that only leads to confusion. 尽管在定义列别名时允许使用,但在使用列别名时不允许使用它们,这样只会导致混淆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM