[英]Sql return empty cell in subquery
我有两个表:
transfers
| No_ | PostingDate | Code |
comments
| No_ | comment |
一次转移可以有很多评论。
我需要创建一个查询,该查询返回所有转账以及其注释中的前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_
我有这个,但它只返回带有注释的传输。
我该如何退回所有转账,如果转账没有评论,则返回空评论。
将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_
我可能倾向于使用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;
这假定您要一个注释,并且当没有注释时,您需要一个空字符串。
笔记:
ORDER BY
子句,但尚不清楚如何选择一个注释。 JOIN
语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.