2012-01-20 192 views
0

我有一個客戶表,下面列SQL父子關係查詢

CustomerID, CustomerName, ParentCustomerID 

如何讓誰擁有從該表中數量最多的孩子們的客戶?

回答

1

像這樣的東西應該可以工作,但我懷疑這是最有效的方式。

另外我還沒有自己運行,所以它可能需要一點點按摩才能使它工作。 :)

select customerId, CustomerName 
from 
    customers 
where customerId = (
    select top 1 ParentCustomerID 
    from 
     customers 
    group by ParentCustomerID 
    order by count(*) desc 
) 
0

你可以嘗試這樣的事:

;WITH CTE(ChildCount, ParentCustomerID) 
AS 
(
    SELECT 
      COUNT(customerID) ChildCount, 
      ParentCustomerID 
    FROM TABLE 
    GROUP BY ParentCustomerID 
) 
SELECT TABLE.CustomerId, TABLE.CustomerName 
FROM CTE 
INNER JOIN TABLE 
ON 
TABLE.CustomerId = CTE.ParentCustomerID 
AND 
CTE.ChildCount = (SELECT MAX(ChildCount) FROM CTE); 
+0

謝謝..它的工作原理。 –

0

試試這個Stamtent解決問題

SELECT TOP 1 ParentCustomerID, COUNT(customerID) 
FROM customer 
GROUP BY ParentCustomerID 
1

我想你會想這樣。

select top 1 
    PARENT.CustomerID, 
    NumberOfChildren = count(CHILD.CustomerID) 
from customers PARENT 
left join customers CHILD on PARENT.CustomerID = CHILD.ParentCustomerID 
group by PARENT.CustomerID 
order by NumberOfChildren desc 

這樣就避免了通過將表連接到自身並且可以非常有效地進行子查詢。