组合多个结果并选择非空值,或者如果所有结果都返回null,则指定null

时间:2017-02-02 14:49:53

标签: sql sql-server tsql reporting

我有一个视图,其中的记录是这样的:

enter image description here

我想查询并返回报告的结果(没有任何可用的BI工具,仅使用SSMS):

enter image description here

我试过了:

select distinct A.Document_Title, A.First_Reviewer, A.Second_Reviewer, A.Third_Reviewer,
(select B.First_review from View as B where B.Title = A.Title) as First_Review,
(select B.Second_review from View as B where B.Title = A.Title) as Second_Review,
(select B.Third_review from View as B where B.Title = A.Title) as Third_Review
From
View A

我收到错误,因为我的子查询返回了多个结果,我也尝试过使用Coalesce但是意识到它用于组合多个列。 任何帮助表示赞赏。谢谢。

1 个答案:

答案 0 :(得分:0)

您似乎只需要group by

select a.document_title,
       a.first_reviewer, a.second_reviewer, a.third_reviewer,
       max(first_review) as first_review,
       max(second_review) as second_review,
       max(third_review) as third_review
from viewA a
group by a.document_title, a.first_reviewer, a.second_reviewer;

你的观点可能很糟糕。此聚合应该可能在视图中发生。如果它使用pivot,则查询可能会留在不必要的列中。