如何應用SQL停止推理。本站提示廣大學習愛好者:(如何應用SQL停止推理)文章只能為提供參考,不一定能成為您想要的結果。以下是如何應用SQL停止推理正文
數據庫環境:SQL SERVER 2008R2
有如下需求:
Baker, Cooper, Fletcher, Miller and Smith住在一座房子的不同樓層。
Baker 不住頂層。Cooper不住底層。
Fletcher 既不住頂層也不住底層。Miller住得比Cooper高。
Smith住的樓層和Fletcher不相鄰。
Fletcher住的樓層和Cooper不相鄰。
用SQL寫出來
解題思緒:
先完成一切人住樓層的陳列組合,然後把條件套出來即求得。如何完成陳列組合,
1.根底數據預備
--預備根底數據,用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
樓層布置如下:
經過以上的代碼的引見,希望對大家的學習有所協助。