如果计数器大于一,则将计数器附加到另一列查询

问题描述

我正在努力为以下查询找到简单的解决方

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

解决方法

如果无法访问一些示例数据,这有点像赌博,但请尝试一下。

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,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() 为此目的很方便,原因有两个:

  1. 它忽略 NULL 值。
  2. 它会自动将数字转换为字符串。