數(shù)據(jù)庫環(huán)境:SQL SERVER 2008R2
有如下需求:
Baker, Cooper, Fletcher, Miller and Smith住在一座房子的不同樓層。
Baker 不住頂層。Cooper不住底層。
Fletcher 既不住頂層也不住底層。Miller住得比Cooper高。
Smith住的樓層和Fletcher不相鄰。
Fletcher住的樓層和Cooper不相鄰。
用SQL寫出來
解題思路:
先實(shí)現(xiàn)所有人住樓層的排列組合,然后把條件套進(jìn)去即求得。如何實(shí)現(xiàn)排列組合,
1.基礎(chǔ)數(shù)據(jù)準(zhǔn)備
--準(zhǔn)備基礎(chǔ)數(shù)據(jù),用A、B、C、D、E分別表示Baker, Cooper, Fletcher, Miller and Smith
CREATE TABLE ttb
(
subname VARCHAR(1) ,
realname VARCHAR(10)
)
INSERT INTO ttb
VALUES ( 'A', 'Baker' ),
( 'B', 'Cooper' ),
( 'C', 'Fletcher' ),
( 'D', 'Miller' ),
( 'E', 'Smith' )
2.生成所有可能情況的排列組合
--生成A、B、C、D、E所有的排列組合
WITH x0
AS ( SELECT CONVERT(VARCHAR(10), 'A') AS hid
UNION ALL
SELECT CONVERT(VARCHAR(10), 'B') AS hid
UNION ALL
SELECT CONVERT(VARCHAR(10), 'C') AS hid
UNION ALL
SELECT CONVERT(VARCHAR(10), 'D') AS hid
UNION ALL
SELECT CONVERT(VARCHAR(10), 'E') AS hid
),
x1
AS ( SELECT hid
FROM x0
WHERE LEN(hid) = 5
UNION ALL
SELECT CONVERT(VARCHAR(10), a.hid + b.hid) AS hid
FROM x0 a
INNER JOIN x1 b ON CHARINDEX(a.hid, b.hid, 1) = 0
)
SELECT hid AS name
INTO #tt
FROM x1
WHERE LEN(hid) = 5
ORDER BY hid
3.加入條件,找出滿足要求的樓層安排
WITH x2
AS ( SELECT name
FROM #tt
WHERE SUBSTRING(name, 5, 1) > 'A'--Baker 不住頂層
AND SUBSTRING(name, 1, 1) > 'B'--Cooper不住底層
AND ( SUBSTRING(name, 1, 1) > 'C'
AND SUBSTRING(name, 5, 1) > 'C'--Fletcher 既不住頂層也不住底層
)
AND name LIKE '%B%D%'--Miller住得比Cooper高
AND name NOT LIKE '%CE%' AND name NOT LIKE '%EC%' --Smith住的樓層和Fletcher不相鄰
AND name NOT LIKE '%BC%' AND name NOT LIKE '%CB%' --Fletcher住的樓層和Cooper不相鄰
),
x3--生成樓層號
AS ( SELECT number AS id ,
SUBSTRING(x2.name, number, 1) AS name
FROM master.dbo.spt_values
INNER JOIN x2 ON 1 = 1
WHERE type = 'P'
AND number = 5
AND number >= 1
)
SELECT a.id AS 樓層,
b.realname AS 姓名
FROM x3 a
INNER JOIN ttb b ON b.subname = a.name
ORDER BY id
樓層安排如下:
通過以上的代碼的介紹,希望對大家的學(xué)習(xí)有所幫助。
您可能感興趣的文章:- python 示例分享---邏輯推理編程解決八皇后