[英]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 JOIN
和COALESCE
一起用空注释替换缺少的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: 笔记:
ORDER BY
clause, but it is unclear how you want to choose the one comment. ORDER BY
子句,但尚不清楚如何选择一个注释。 JOIN
syntax. JOIN
语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.