如何使用位列进行分组?

How to group by using bit column?

我的table数据

id  quota  
1  0  
1  NULL  
1  1  
2  0  
2  NULL  
3  NULL  

结果 I 除了

id  quota  
1  1  
2  0  
3  NULL  

我得到的结果:

id  quota  
1  1  
2  0  
3  0  

我正在使用的查询:

 select id,count(id) count_id,
 case when max(coalesce(quota,0)) = 1 then 1
 when max(coalesce(quota,0)) = 0 then 0
 else null 
 end as quota from forbit group by i  

我的列配额数据类型是位。

我希望组中最大值为 1 时将配额设为 1,组中最大值为 0 时将配额设为 0,组中最大值为空时将配额设为空。 我基本上想为 id 3 实现 NULL。

类似 post 我看到了: Use column of type bit to differentiate group by?

我认为只是一个简单的 max 就是您正在寻找的,在转换为 int 之后,因为 maxbit 上不起作用。

declare @Test table (id int, quota bit);

insert into @Test (id, quota)
values
(1, 0)
, (1, NULL)
, (1, 1)  
, (2, 0) 
, (2, NULL)  
, (3, NULL);

select id, max(convert(int,quota))
from @Test
group by id;  

Returns:

id  quota
1   1
2   0
3   NULL

看来你想多了,你可以通过如下简单的查询来完成:

select max(cast(quota) as int) as max_val, id
from test
group by id