表結構與數據:https://github.com/XuePeng87/TSQLV4git
每一個子查詢都具備一個其所隸屬的外部查詢。自包含子查詢是獨立於其所隸屬的外部查詢的。看一個自包含子查詢示例:github
SELECT orderid, orderdate, empid, custid FROM Sales.Orders WHERE orderid = (SELECT MAX(O.orderid) FROM Sales.Orders AS O)
使用"="的話,子查詢若是返回多行則會使查詢失敗。若子查詢返回NULL,與NULL比較會生成UNKNOWN,查詢篩選不返回拆選表達式計算爲NUKNOWN的行。sql
若是子查詢返回的是多行,能夠使用IN處理,例如:spa
SELECT orderid, orderdate, empid, custid FROM Sales.Orders WHERE empid IN ( SELECT E.empid FROM HR.Employees AS E WHERE E.lastname LIKE N'D%' );
相關子查詢引用的表位於外部查詢中,這意味該子查詢依賴於外部查詢而且沒法單獨調用。例如:code
SELECT custid, orderid, orderdate, empid FROM Sales.Orders AS O1 WHERE orderid = ( SELECT MAX(O2.orderid) FROM Sales.Orders AS O2 WHERE O2.custid = O1.custid );
上面例子中,子查詢使用了外部表O1的字段,因此是相關子查詢。get
T-SQL支持一個叫作EXISTS的謂詞,可接受一個子查詢做爲輸入,若是子查詢返回人一行,謂詞返回TRUE,不然返回FALSE。例如,查詢返回下訂單的西班牙客戶:qt
SELECT custid, companyname FROM Sales.Customers AS C WHERE country = N'Spain' AND EXISTS ( SELECT * FROM Sales.Orders AS O WHERE O.custid = C.custid );
EXISTS使用的是兩值邏輯,而不是三值邏輯。it
爲每一個訂單返回當前訂單信息,以及前一個訂單的ID:ast
SELECT orderid, orderdate, empid, custid, ( SELECT MAX(O2.orderid) FROM Sales.Orders AS O2 WHERE O2.orderid < O1.orderid ) AS prevorderid FROM Sales.Orders AS O1;
返回每一年的訂單年度、數量和通過年度的運行總量。也就是說,每年,計算到以前年度的數量之和。例如:class
SELECT orderyear, qty, ( SELECT SUM(O2.qty) FROM Sales.OrderTotalsByYear AS O2 WHERE O2.orderyear <= O1.orderyear ) AS runqty FROM Sales.OrderTotalsByYear AS O1 ORDER BY orderyear;