【问题标题】:Append counter with another column of query if counter is greater than one如果计数器大于一,则将计数器附加到另一列查询中
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 谢谢。我仍然需要在此查询中添加更多内容,但这将在一定程度上帮助我:)
【解决方案2】:

嗯嗯。 . .

我可能会建议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. 它会自动将数字转换为字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-08
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-20
    • 2011-10-27
    • 1970-01-01
    相关资源
    最近更新 更多