嘗試這樣:
DECLARE @Words TABLE (Word VARCHAR(20) PRIMARY KEY)
INSERT INTO @Words (Word) VALUES ('Adam'), ('John'), ('Alex'), ('Bob'), ('Barbara'),('Cabral')
DECLARE @Letters VARCHAR(10)
SET @Letters='ABCD'
DECLARE @Numbers TABLE(N INT PRIMARY KEY)
INSERT INTO @Numbers (N) VALUES (1)
WHILE @@ROWCOUNT<512
INSERT INTO @Numbers (N)
SELECT N+(SELECT COUNT(*) FROM @Numbers) FROM @Numbers
DECLARE @Combinations TABLE (N INT PRIMARY KEY, SelectedLetters VARCHAR(10))
INSERT INTO @Combinations (N, SelectedLetters)
SELECT *, (
SELECT SUBSTRING(@Letters,N2.N,1) AS '*'
FROM @Numbers N2
WHERE N2.N<=LEN(@Letters)
AND N1.N & POWER(2,N2.N-1)<>0
FOR XML PATH(''), TYPE
).value('.','varchar(10)') AS SelectedLetters
FROM @Numbers N1
WHERE N1.N<POWER(2,LEN(@Letters))
ORDER BY 1,2
DECLARE @AllCounts TABLE (
Word VARCHAR(20) NOT NULL,
N INT NOT NULL,
PRIMARY KEY (Word,N),
SelectedLetters VARCHAR(10) NOT NULL,
Cnt INT NOT NULL
)
INSERT INTO @AllCounts
SELECT W.Word, C.N, C.SelectedLetters, X.Cnt
FROM @Words W
CROSS JOIN @Combinations C
CROSS APPLY (
SELECT COUNT(*) AS Cnt
FROM @Numbers N
WHERE SUBSTRING(W.Word,N,1) LIKE '%['+c.SelectedLetters+']%'
) X
WHERE X.Cnt>0
ORDER BY 1,2
SELECT * FROM @AllCounts A1
WHERE NOT EXISTS (
SELECT * FROM @AllCounts A2
WHERE A1.Word=A2.Word
AND A1.N<>A2.N
AND A1.N | A2.N = A1.N
AND A1.Cnt=A2.Cnt
)
的@Combinations表存儲了所有可能的字母組合。 我們計算每個單詞到@AllCounts表中的計數。最後,我們只顯示相關計數。
期望的結果是什麼? –
它應該是這樣的: 組合量 b 9分配 A + B 7 A + B + C 6 等..... –
仍不清楚,你能包括一些示例數據和預期的結果?請包括在問題中。 –