2016-06-27 213 views
-1

我理解此相關子查詢的問題:SQL - 相關子查詢

SELECT Country, CustomerID, 
    (SELECT COUNT(*) 
    FROM Customers AS CustomersInner 
    WHERE CustomersInner.CustomerID < CustomersOuter.CustomerID 
    AND CustomersInner.Country=CustomersOuter.Country) + 1 
AS customer_seq_num 
FROM Customers AS CustomersOuter ORDER BY Country; 

這個例子來自http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all

如何做到這一點的查詢工作是什麼呢?爲什麼要比較CustomersInner.CustomerID < CustomersOuter.CustomerID?如何解釋+1?更深層的解釋會很棒。

+0

在大多數數據庫中,您可以使用'rank()'來達到此目的。我建議你研究窗口函數。 –

回答

2

對主查詢中的每一行執行相關子查詢。在這種情況下,主查詢是

SELECT Country, CustomerID 
    FROM Customers As CustomersOuter 
ORDER BY Country 

此查詢國家將返回所有客戶ID的順序。

Country | Customer ID 
----------------------- 
Argentina | 12 
Argentina | 54 
Argentina | 64 
Austria | 20 
Austria | 59 

爲每個國家/客戶ID對執行相關子查詢。在這種情況下:

對於第一行:

SELECT COUNT(*) 
    FROM Customers AS CustomersInner 
WHERE CustomersInner.CustomerID < 12 
    AND CustomersInner.Country='Argentina') + 1 

至於有沒有在阿根廷與ID < 12客戶count(*)回報與+1零,你得到1

對於第二行:

SELECT COUNT(*) 
    FROM Customers AS CustomersInner 
WHERE CustomersInner.CustomerID < 54 
    AND CustomersInner.Country='Argentina') + 1 

結果將會是1(習慣merID = 12)+ 1 = 2

等等...

當你改變國家時,count(*)零重新開始,讓您擁有一個運行計數器:每個國家統計的客戶數量。

Country | Customer ID | customer_seq_num 
------------------------------------------ 
Argentina | 12   | 1 
Argentina | 54   | 2 
Argentina | 64   | 3 
Austria | 20   | 1 <--- change country, reset counter (no customerID < 20 in 'Austria') 
Austria | 59   | 2