简体   繁体   中英

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.

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:

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:

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.
  • Do not use implicit JOIN syntax.
  • 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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