我正在努力为下面的查询找到简单的解决方案
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,则使用groupid追加count,否则返回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?
如果不能访问一些样本数据,这有点冒险,但请尝试一下。
SELECT
Id,
TotalCount,
GroupId,
CASE
WHEN GroupId is not null AND TotalCount > 1 THEN GroupId || '-' TotalCount
WHEN GroupId is not null AND TotalCount = 1 THEN GroupId
ELSE null END as FinalGroupId
FROM
(
SELECT
Id,
GroupId,
SUM( CASE WHEN IsActive = 1 THEN 1 ELSE 0 END ) as TotalCount
FROM
table
GROUP BY
Id, GroupId
) g
嗯。
我可能会建议left join
和聚合,例如简化表达式:
select t1.id, t1.groupid, count(t2.id) as cnt,
concat(t1.groupid,
case when count(t2.id) > 0 then concat('-', count(t2.id)) end
) as newcol
from table1 t1 left join
table2 t2
on t2.id = t1.id
group by t1.id, t1.groupid;
concat()
方便用于此目的有两个原因:
- 它忽略
NULL
值 - 它会自动将数字转换为字符串