评估多行并汇总到新列

时间:2018-10-12 17:11:14

标签: sql sql-server database

我正在尝试评估一列中的值,以确定行的每个子集的值。更容易解释...

select distinct
    app_id,
    asset_id,
    asset_migration_scope
from
    table

这是输出示例:

app_ID   asset_id   asset_migration_scope

123      asset1     Migrating

123      asset2     Migrating

123      asset3     Not Migrating

456      asset1     Migrating

456      asset2     Migrating

789      asset1     Not Migrating

789      asset2     Not Migrating

我想做的是创建第四列来汇总这些内容。如果给定应用程序ID的所有资产=正在迁移,则该应用程序ID的每一行的值将为正在迁移。如果混合使用“迁移” /“不迁移”,则将其称为“混合”。全部为“未迁移”,即为“未迁移”

输出如下:

app_ID   asset_id   asset_migration_scope    app_migration_scope

123      asset1     Migrating                Hybrid

123      asset2     Migrating                Hybrid

123      asset3     Not Migrating            Hybrid

456      asset1     Migrating                Migrating

456      asset2     Migrating                Migrating

789      asset1     Not Migrating            Not Migrating

789      asset2     Not Migrating            Not Migrating

如何进行汇总,以便我们查看每个app_id + asset_id组合以及相应的asset_migration_scope值,以便基于app_id确定app_migration_scope列的单个值?

非常感谢!

1 个答案:

答案 0 :(得分:2)

您可以将case表达式与聚合一起使用:

SELECT t.app_id, t.asset_id, t.asset_migration_scope,
       (CASE WHEN mn_scope <> mx_scope 
             THEN 'Hybrid' 
             WHEN (mn_scope = mx_scope AND mn_scope = 'Migrating')
             THEN 'Migrating'
             WHEN (mn_scope = mx_scope AND mn_scope = 'Not Migrating')
             THEN 'Not Migrating'
        END) AS app_migration_scope 
FROM table t CROSS APPLY
     (SELECT MIN(t1.asset_migration_scope) AS mn_scope, MAX(t1.asset_migration_scope) AS mx_scope
      FROM table t1
      WHERE t1.app_ID = t.app_ID
     ) t1;

但是,DISTINCT可以克服,因为您的样本数据不建议我使用DISTINCT