SQL 按位组设置?
SQL group by bit set?
有什么方法可以按列中设置的各个位对 select 的结果进行分组吗?也就是说,忽略各种位的组合(否则一个简单的 group by column
就足够了)。
例如,假设 table 的 group-by 列的值从 1 到 10 恰好一次(下面以二进制表示形式呈现以简化以下 group-by 语句的 construction/verification结果):
1 0001
2 0010
3 0011
4 0100
5 0101
6 0110
7 0111
8 1000
9 1001
10 1010
我想要实现的分组效果是这样的:
select <bit>, count(*), group_concat(<column>) from <table> group by <...>
0 5 1,3,5,7,9
1 5 2,3,6,7,10
2 4 4,5,6,7
3 3 8,9,10
假设第一位是"bit 0"。
我现在正在使用 MySQL,所以理想情况下应该有一个解决方案;但我会对其他 RDBMS 解决方案感兴趣,如果有的话。
您需要拆分值然后重新聚合。像这样:
select n.n, group_concat(col1)
from t join
(select 0 as n union all select 1 union all select 2 union all select 3
) n
on (1 << n) & bits > 0
group by n;
有什么方法可以按列中设置的各个位对 select 的结果进行分组吗?也就是说,忽略各种位的组合(否则一个简单的 group by column
就足够了)。
例如,假设 table 的 group-by 列的值从 1 到 10 恰好一次(下面以二进制表示形式呈现以简化以下 group-by 语句的 construction/verification结果):
1 0001
2 0010
3 0011
4 0100
5 0101
6 0110
7 0111
8 1000
9 1001
10 1010
我想要实现的分组效果是这样的:
select <bit>, count(*), group_concat(<column>) from <table> group by <...>
0 5 1,3,5,7,9
1 5 2,3,6,7,10
2 4 4,5,6,7
3 3 8,9,10
假设第一位是"bit 0"。
我现在正在使用 MySQL,所以理想情况下应该有一个解决方案;但我会对其他 RDBMS 解决方案感兴趣,如果有的话。
您需要拆分值然后重新聚合。像这样:
select n.n, group_concat(col1)
from t join
(select 0 as n union all select 1 union all select 2 union all select 3
) n
on (1 << n) & bits > 0
group by n;