Reputation: 571
I'm trying to evaluate values from a column to determine a value for each subset of rows. Easier to explain...
select distinct
app_id,
asset_id,
asset_migration_scope
from
table
Here's an example of the output:
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
What I'd like to do is create a fourth column that rolls these up. If all assets for a given application ID = Migrating, the value for every row for that Application ID would be Migrating. If it's a mix of Migrating/Not Migrating, we'd call it Hybrid. All "Not Migrating", it'd be "Not Migrating"
The output would look as follows:
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
How can I do this roll-up so that we look at each app_id + asset_id combination with the corresponding asset_migration_scope values to determine a single value for the app_migration_scope column based on app_id?
Huge thanks in advance!
Upvotes: 0
Views: 36
Reputation: 50173
You can use case
expression with aggregation :
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;
However, DISTINCT
would be overcome as your sample data doesn't suggests me to use DISTINCT
.
Upvotes: 2