合并 SQL 查询中的记录集值

Merge recordset values in SQL query

给定以下结果集:

我要合并:

  1. 'Verifying' 和 'Verified' 行为 Verification_stage,
  2. 'Reviewing' 和 'Reviewed' 行为 Reviewing_stage 和
  3. 'Analyzing' 和 'Analyzed' 行为 Analysis_stage
  4. 汇总了各自的整数

所以我得到了以下结果集:

HAUT-53 | Verification_stage | 677.579 | 6
HAUT-53 | Reviewing_stage    | 516.409 | 2
HAUT-53 | Open               | 70.629  | 1
HAUT-53 | Implementing       | 7       | 1
HAUT-53 | Analysis_stage     | 12.027  | 2

有什么想法吗?

这是您的问题。您可以使用 sum() 汇总您的 column3。然后 group by 个阶段。

select col1, 
    , case when col2 in ('Verifying', 'Verified') then 'Verification_Stage'
        when col2 in ('Reviewing', 'Reviewed') then 'Reviewing_Stage'
        when col2 in ('Analyzing', 'Analyzed') then 'Analyzing_Stage'
        else col2 end
    , sum(col3) 
    , sum(col4)
from tableA
group by col1,
    case when col2 in ('Verifying', 'Verified') then 'Verification_Stage'
        when col2 in ('Reviewing', 'Reviewed') then 'Reviewing_Stage'
        when col2 in ('Analyzing', 'Analyzed') then 'Analyzing_Stage'
        else col2 end

您可以使用多个 case 表达式,并启用聚合。你没有给出你的列的名称所以我假设 col1, col2, col3, col4.

select
    col1,
    case 
        when col2 in ('Verifying', 'Verified') then 'Verification_stage'
        when col2 in ('Reviewing', 'Reviewed') then 'Reviewing_stage'
        when col2 in ('Analyzing', 'Analyzed') then 'Analysis_stage'
        else col2
    end new_col2
    max(col3) max_col3,
    sum(col4) sum_col4
from mytable
group by 
    col1,
    case 
        when col2 in ('Verifying', 'Verified') then 'Verification_stage'
        when col2 in ('Reviewing', 'Reviewed') then 'Reviewing_stage'
        when col2 in ('Analyzing', 'Analyzed') then 'Analysis_stage'
        else col2
    end

如果除了您列出的值之外没有其他值,则可以缩短如下:

select
    col1,
    case 
        when col2 like 'Verif%' then 'Verification_stage'
        when col2 like 'Review%' then 'Reviewing_stage'
        when col2 like 'Analyz%' then 'Analysis_stage'
        else col2
    end new_col2
    max(col3) max_col3,
    sum(col4) sum_col4
from mytable
group by 
    col1,
    case 
        when col2 like 'Verif%' then 'Verification_stage'
        when col2 like 'Review%' then 'Reviewing_stage'
        when col2 like 'Analyz%' then 'Analysis_stage'
        else col2
    end

旁注:很少有 RDBMS 支持 group by 子句中的列别名(MySQL 是一个示例);这使您有机会缩短 group by 子句:

group by col1, new_col2

在导出的table中使用case表达式进行合并。然后GROUP BY其结果:

select c1, c2, sum(c3), sum(c4)
from
(
    select c1, 
           case when c2 in ('Verifying', 'Verified') then 'Verification_Stage'
                when c2 in ('Reviewing', 'Reviewed') then 'Reviewing_Stage'
                when c2 in ('Analyzing', 'Analyzed') then 'Analyzing_Stage'
                else c2 
           end c2,
           c3, c4
    from tablename
) dt
group by c1, c2

使用派生的 table(子查询)意味着您不必重复 case 表达式。不易出错,更易于维护 - 并且符合 ANSI SQL!