问题
I have an empty table with 7 BIT columns (A, B, C, D, E, F, and G). I am looking to populate this table with rows representing all possible combinations of these columns. Ideally there would be no rows containing duplicates of the exact same combinations. Although I am showing 7 columns here, the number of columns could be greater, so the solution should be scalable.
A snippet of the table after being populated would look similar to below:
Ideally this would be based on an INSERT statement, but I am open to a T-SQL Loop solution as well. I have tried using CROSS JOINS, but my limited knowledge has not gotten me very far.
Any help would be greatly appreciated.
回答1:
Use a CTE and CROSS JOIN
it with itself 7 times, as in:
with bits as (select 0 as bit union select 1)
select
row_number() over(
order by a.bit, b.bit, c.bit, d.bit, e.bit, f.bit, g.bit) as id,
a.bit, b.bit, c.bit, d.bit, e.bit, f.bit, g.bit
from bits a
cross join bits b
cross join bits c
cross join bits d
cross join bits e
cross join bits f
cross join bits g
回答2:
You can use the following query
;with bits as (select * from (values(0),(1)) as bits(d))
select *
from
bits as b1,
bits as b2,
bits as b3,
bits as b4,
bits as b5,
bits as b6,
bits as b7
回答3:
You can do it with recursion.
This solution is less performant than the previous one, I know, because it makes all possible permutations
but at least, it has the advantage that it's scalable on the permutation number
declare @mytable as table (s varchar(10))
insert into @mytable values('1'),('0');
with cte as(
select 0 as perm,cast(s as varchar(10)) s from @mytable
union all
select perm+1,cast(t1.s+t2.s as varchar(10)) from cte t1 inner join @mytable t2 on 1=1
where perm <=7)
select * from cte where perm=7 order by s
来源:https://stackoverflow.com/questions/59971453/sql-server-all-possible-combinations-of-bit-columns