我有两张桌子:
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_
我有这个,但它只返回带注释的传输。
如何返回所有转移,如果转移没有评论,则返回空注释。
答案 0 :(得分:3)
使用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_
答案 1 :(得分:1)
我可能倾向于使用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
语法。