我有一个包含以下列的客户表
CustomerID, CustomerName, ParentCustomerID
如何从此表中获得拥有最多子女数量的客户?
答案 0 :(得分:1)
这样的事情应该有效,但我怀疑这是最有效的方法。
此外,我自己也没有这样做,所以可能需要一点点按摩才能让它发挥作用。 :)
select customerId, CustomerName
from
customers
where customerId = (
select top 1 ParentCustomerID
from
customers
group by ParentCustomerID
order by count(*) desc
)
答案 1 :(得分: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
这样就可以通过将表连接到自身来避免子查询的需要,并且非常有效。
答案 2 :(得分: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);
答案 3 :(得分:0)
尝试使用此Stamtent来解决问题
SELECT TOP 1 ParentCustomerID, COUNT(customerID)
FROM customer
GROUP BY ParentCustomerID