【发布时间】:2021-07-11 15:53:36
【问题描述】:
我正在努力为以下查询找到简单的解决方案
select id,
(select count(1) from table2 where table2.Id = table1.Id and table2.IsActive = 1) as TotalCount,
groupid from table1
现在我想在这个查询中再添加一个字段 FinalGroupId。
FinalGropId = 如果 Totalcount 大于 1 且 groupid 不为 null,则将 count 附加到 Groupid 或返回 groupid 。
以下是预期结果。
----------------------------------------------------------
Id | TotalCount | GroupId |FinalGroupId
---------------------------------------------------------
1 | 1 | 11111 | 11111
2 | 2 | 22222 | 22222-2
3 | 1 | 33333 | 33333
4 | 3 | 44444 | 44444-3
5 | 3 | null | null
如何以优化的方式找到FinalGroupId?
【问题讨论】:
-
请将示例数据添加到您的问题中,以产生您提供的结果。还将数据添加为可编辑文本,而不是图像
-
@NickW 我已经更新了问题。基本上 FinalGroupId 是我想要获得的预期结果,基于 TotalCount 和 GroupId
-
嗨 - 您尚未添加会产生您给出的结果的源数据
-
TotalCount 和 GroupId 是生成 FinalGroupId 的源数据
-
源数据表示 table1 和 table2 中的实际行值集,它们将产生您给出的输出。
标签: sql mssql-jdbc