2016-06-21 8 views
0

私はいくつかの問題を抱えています....どのように私は顧客の合計として以下の表を返すように修正次のコードを取得しますか?顧客の合計数量、そしてトップ10のリストが必要です。イエローローズはすべて一緒に追加して、1つのエントリとしてカウントする必要があります。お客様のトップ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

あなたの内側のクエリでGROUP BY句からTkscale.Qtyを削除

+0

ありがとうございます!今私の次のステップに...私はおそらく戻ってくるでしょう。 – Molly

1

'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でグループ化する必要があります(魔法は索引付けするべきではありません...): 'group by Tkscale.CustomerID' – marlan

関連する問題