客户排名前10位 - 总计

时间:2016-06-21 13:26:03

标签: sql sql-server sum

我遇到了一些问题....如何修复以下代码以将下表作为客户总数返回?我希望客户总共有客户数量,然后是前十名。所以所有的黄玫瑰应该加在一起,然后算作一个条目,而不是所有的货物单独出现。

select top 10 T1.Quantity, T1.CustName
from
(
select 
     SUM(Tkscale.Qty)Quantity,
        Slcust.Name CustName

from Tkscale with (nolock)
      left outer join Slcust with (nolock) on Tkscale.CustomerID = Slcust.CustomerID 

group by Tkscale.CustomerID, Tkscale.Qty, Slcust.Name
) T1
order by T1.CustName desc, T1.Quantity desc

enter image description here

2 个答案:

答案 0 :(得分:3)

尝试删除分组'Tkscale.Qty'

答案 1 :(得分:1)

从内部查询中的Tkscale.Qty子句中删除GROUP BY。我还认为您希望按数量排名前十大客户,而不是名字:

select top 10 T1.Quantity, T1.CustName
from
(
select 
     SUM(Tkscale.Qty)Quantity,
        Slcust.Name CustName

from Tkscale with (nolock)
      left outer join Slcust with (nolock) on Tkscale.CustomerID = Slcust.CustomerID 

group by Slcust.Name
) T1
order by T1.Quantity desc, T1.CustName desc
         ^ change the sequence of the ORDER BY clause