2016-06-21 68 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