SQL Server Updating values based on a group of records

3phpmpom  于 2023-06-04  发布在  其他
关注(0)|答案(3)|浏览(169)

I'm trying to carry out an update on the "Keys" column, where Janitor value is set to "No_Name". It should be updated to "None" only when all Janitors have a NULL value per Building Name. When a Janitor(s) do have a Key then set 'No_Name' as NULL still.
| Building Name | Janitor | Keys | Notes |
| ------------ | ------------ | ------------ | ------------ |
| Building A | Andrew | Yes | |
| Building A | Mike | Yes | |
| Building A | Bill | NULL | |
| Building A | Phil | Yes | |
| Building A | No_Name | NULL | --- should stay NULL |
| Building B | Andrew | NULL | |
| Building B | Mike | NULL | |
| Building B | Bill | NULL | |
| Building B | Phil | NULL | |
| Building B | No_Name | NULL | --- should change to 'NONE' bcs no Owners have the keys |

Tried a bunch of AND/OR statements with no success.

nzk0hqpo

nzk0hqpo1#

You could use an updatable table expression making use of a window aggregate:

update t 
  set Keys = case when k is null then 'None' end
from (
  select *, Max(keys) over(partition by Building_Name) k
  from t
)t
where Janitor = 'No_Name';
9rygscc1

9rygscc12#

I dont know the exact DBMS you're using, but the idea is generally the same. You can use aggregation function like MAX() on Keys to generate list of buildings to update to None.

select "Building name"
from No_Name
group by "Building name"
having max(keys) <> NULL

this query will give you all building that have all NULL values in keys, then you can incorporate it in Update statement.

2lpgd968

2lpgd9683#

You can try going with an EXISTS expression.

UPDATE tab
SET Keys = 'None'
WHERE Janitor = 'No_Name'
  AND NOT EXISTS(SELECT 1 
                 FROM tab t2 
                 WHERE tab.BuildingName = t2.BuildingName AND t2.Keys IS NOT NULL);

Output:

BuildingNameJanitorKeys
Building AAndrewYes
Building AMikeYes
Building ABillnull
Building APhilYes
Building ANo_Namenull
Building BAndrewnull
Building BMikenull
Building BBillnull
Building BPhilnull
Building BNo_NameNone

Check the demo here .

相关问题