2016-06-21 62 views
0

我遇到了一些问题....我如何获得下面的代码以返回下面的表作为客户总和?我想要客户提供的总客户数量,然后是前10名。所以所有的黄玫瑰应该加在一起,然后算作一个入口,而不是单独出现所有的货物。客户排名前10位 - 总计

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

+0

2008 R2 @CodeDifferent – Molly

+1

在内部查询通过tkscale.qty不群。这是总结,所以它不应该在组中。 – xQbert

+0

在继续使用nolock提示丢弃数据库之前,您可能需要阅读本文。 http://blogs.sqlsentry.com/aaronbertrand/bad-habits-nolock-everywhere/ –

回答

3

尝试在分组 'Tkscale.Qty'

+0

谢谢!现在进入下一步......我可能会回来。 – Molly

1

GROUP BY子句中你内心的查询中删除Tkscale.Qty删除。我也认为你的数量要前10大客户,而不是他们的名字:

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 
+0

你应该按照索引ID进行分组,而不是一个字符串值(女巫不应该编入索引...):'Tkscale.CustomerID'组 – marlan