与我上一篇文章类似,但深入挖掘一下。本报告的下一个任务是列出每个位置的前10位客户 - 例如:00468,00469,00471等的前10位客户
select top 10 T1.LocationID, T1.CustName, T1.Quantity--, t1.Salesperson
from
(
select
SUM(Tkscale.Qty)Quantity,
Slcust.Name CustName,
Slperson.Name Salesperson,
Inlocat.LocationID LocationID,
Inlocat.Description Location
from
Tkscale
left outer join Slcust on Tkscale.CustomerID = Slcust.CustomerID
left outer join Slperson on slcust.SalespersonID = Slperson.SalespersonID
left outer join Inlocat on Inlocat.LocationID = Tkscale.LocationID
where
slperson.Name like 'Tammy%'
group by
Inlocat.LocationID, inlocat.description, Tkscale.CustomerID, Slcust.Name, Slperson.Name
) T1
order by T1.Quantity desc, T1.LocationID, T1.CustName
输出:
答案 0 :(得分:0)
使用row_number
SELECT T1.LocationID
,T1.CustName
,T1.Quantity --, t1.Salesperson
FROM (
SELECT SUM(Tkscale.Qty) Quantity
,Slcust.NAME CustName
,Slperson.NAME Salesperson
,Inlocat.LocationID LocationID
,Inlocat.Description Location
,row_number() over (partition by Inlocat.LocationID order by SUM(Tkscale.Qty) desc) rowid
FROM Tkscale
LEFT JOIN Slcust
ON Tkscale.CustomerID = Slcust.CustomerID
LEFT JOIN Slperson
ON slcust.SalespersonID = Slperson.SalespersonID
LEFT JOIN Inlocat
ON Inlocat.LocationID = Tkscale.LocationID
WHERE slperson.NAME LIKE 'Tammy%'
GROUP BY Inlocat.LocationID
,inlocat.description
,Tkscale.CustomerID
,Slcust.NAME
,Slperson.NAME
) T1
where t1.rowid < 11
ORDER BY T1.LocationID
,T1.rowid desc
答案 1 :(得分:0)
select T1.LocationID, T1.CustName, T1.Quantity--, t1.Salesperson
from
(
select
SUM(Tkscale.Qty)Quantity,
Slcust.Name CustName,
Slperson.Name Salesperson,
Inlocat.LocationID LocationID,
Inlocat.Description Location
,NoGapsWithTies = DENSE_RANK() OVER (PARTITION BY Inlocat.LocationID ORDER BY SUM(Tkscale.Qty) DESC)
,WithGapsAndTies = RANK() OVER (PARTITION BY Inlocat.LocationID ORDER BY SUM(Tkscale.Qty) DESC)
,NoGapsNoTiesAbitraryChoiceIfTie = ROW_NUMBER() OVER (PARTITION BY Inlocat.LocationID ORDER BY SUM(Tkscale.Qty) DESC)
from
Tkscale
left outer join Slcust on Tkscale.CustomerID = Slcust.CustomerID
left outer join Slperson on slcust.SalespersonID = Slperson.SalespersonID
left outer join Inlocat on Inlocat.LocationID = Tkscale.LocationID
where
slperson.Name like 'Tammy%'
group by
Inlocat.LocationID, inlocat.description, Tkscale.CustomerID, Slcust.Name, Slperson.Name
) T1
WHERE
--NoGapsWithTies <=10
WithGapsAndTies <= 10
--NoGapsNoTiesAbitraryChoiceIfTie <=10
order by T1.Quantity desc, T1.LocationID, T1.CustName
这是有效的,因为在计算窗函数之前,结果集是由group by构建的。使用DENSE_RANK
会给你带来无间隙的关系,RANK
会给你带来联系和差距,ROW_NUMBER
会给你没有联系,没有差距,但任意选择什么时候他们是客户之间的关系