如何使用 JOINS 和 SUM() 从现有数据生成新的查询结果?

How do I make a new query result from existing data using JOINS and SUM()?

提问人:John D 提问时间:11/16/2023 最后编辑:John D 更新时间:11/16/2023 访问量:45

问:

使用 SQL Server Management Studio v19.1。

我需要帮助。我已经花了几个小时尝试各种连接和聚合来获得结果,但我无法让它为我工作。欢迎您的帮助。

我们有这个查询结果表:

UID_MOTRIP  INT_SEVERITY    BOOL_IS_NOTE_HOT     CountQ1
--------------------------------------------------------
    1           2                   0               2
    1           2                   1               3
    1           4                   0               1

INT_SEVERITY值 2 是“常规”缺陷,值 4 是“热”缺陷。

我们需要这个结果——但我缺乏 SQL 经验......

UID_MOTRIP  RegularDefectsCount HotDefectsCount
-----------------------------------------------
    1               5               1              
sql-服务器

评论


答:

4赞 Littlefoot 11/16/2023 #1

条件聚合可能会有所帮助。使用当前查询作为子查询(或CTE,如果您愿意),例如

select uid_motrip, 
  sum(case when int_severity = 2 then countq1 else 0 end) as regular_count,
  sum(case when int_severity = 4 then countq1 else 0 end) as hot_count
from (select ... --> here goes your current query, the one that
                 --> returns result you posted 
     )
group by uid_motrip;