我需要通过UPDATE
为表中的组“汇总”位值。因此,如果组中的某一行设置为true,则需要将组中的其他行设置为true。
例如,我有一个这样的表:
GroupID | Type | BitA | BitB
------------------------------
1 | Parent | 0 | 0
1 | Child | 1 | 0
2 | Parent | 0 | 0
2 | Child | 1 | 1
2 | Child | 0 | 1
3 | Parent | 0 | 0
3 | Child | 0 | 0
在UPDATE
语句之后的预期结果将是:
GroupID | Type | BitA | BitB
------------------------------
1 | Parent | 1 | 0
1 | Child | 1 | 0
2 | Parent | 1 | 1
2 | Child | 1 | 1
2 | Child | 0 | 1
3 | Parent | 0 | 0
3 | Child | 0 | 0
由于第1组的子级的BitA设置为true,因此父级也应设置为true。
我唯一能找到的就是首先将位转换为int以便将其聚合到组中,但是好像我要钻进兔子洞了。
SELECT
MAX(CAST(BitA as int)),
MAX(CAST(BitB as int))
FROM MyTable
WHERE Type = 'Child'
GROUP BY GroupID
有更简单的方法吗?
答案 0 :(得分:2)
您似乎想基于子级设置父级标志:
with toupdate as (
select t.*,
max(BitA) over (partition by groupid) as max_bitA,
max(BitB) over (partition by groupid) as max_bitB
from mytable t
)
update toupdate
set BitA = max_BitA,
BitB = max_BitB
where BitA <> max_BitA or BitB <> max_BitB;
如果您输入的比特确实是bit
,则需要进行一些转换:
with toupdate as (
select t.*,
convert(bit, max(convert(int, BitA)) over (partition by groupid)) as max_bitA,
convert(bit, max(convert(int, BitB)) over (partition by groupid)) as max_bitB
from mytable t
)
update toupdate
set BitA = max_BitA,
BitB = max_BitB
where BitA <> max_BitA or BitB <> max_BitB;
答案 1 :(得分:0)
这可以为您提供所需的东西...
UPDATE M1
SET M1.BITA = 1,
M1.BITB = 1
FROM MYTABLE M1
WHERE EXISTS
(
SELECT 1
FROM MYTABLE M2
WHERE M2.GroupID = M1.GoupID
AND
(
M2.BITA = 1
OR M2.BITB = 1
)
);