與你的表稱爲aTable - 我想出了這個
CREATE TABLE #combo (z bigint);
DECLARE @CNT integer;
SELECT @CNT = COUNT(0) FROM aTable;
DECLARE @I int;
SET @I = 0
WHILE @I < POWER(2, @CNT)
BEGIN
INSERT #combo VALUES(@I);
SET @I = @I + 1;
END
--select * from #combo;
;with cte as (select *, row_number() over (order by id) as rn from aTable),
combs as (select c1.z,cte.rn, cte.val, POWER(2, cte.rn -1) & c1.z as flag from cte join #combo c1 ON POWER(2, cte.rn -1) & c1.z != 0)
select *, row_number() over (partition by z order by rn) as lev, val final_val into #perms from combs order by z,rn;
--select * from #perms;
DECLARE @depth as integer;
SET @depth = 2;
WHILE EXISTS (SELECT 0 FROM #perms WHERE lev = @depth)
begin
UPDATE #perms
SET #perms.final_val = p.final_val & #perms.val
FROM
#perms
INNER JOIN
#perms p
ON
p.lev = #perms.lev - 1 AND p.z = #perms.z
set @depth = @depth + 1;
end
select #perms.z,#perms.final_val from #perms join (SELECT p.z, max(p.lev) maxz FROM #perms p GROUP BY z) DQ ON #perms.lev = dq.maxz and dq.z = #perms.z order by #perms.z;
DROP TABLE #combo;
DROP TABLE #perms;
甚至
with t as
(select * from atable),
cur as
(select id, val from t union all
select t.id, t.val & cur.val from cur join t on cur.id>t.id)
select id,val
from cur
order by id
你準備使用臨時表和遊標/存儲過程的程序邏輯?我假設你想要n條記錄,所以可能會有20條記錄(例如,它仍然有合理的記錄輸出數量!) – Cato
在數據庫中進行位錯很少是一個好主意。如果您想要存儲多個事實,請存儲多行 - 不要將它們全部整理到一個列中。 –