2014-10-08 173 views
1

我已瀏覽論壇,可以找到各種示例來解決我的問題,但不能將所有內容放在一起。使用Group By,Top N和Sum的查詢

我的情況是典型的,我希望按組(Shop_Lookup.ShopGroup))顯示前10位客戶(訂單。[客戶名稱])的總收入。

無論ShopGroup如何,我都可以獲得整體排名前10位的排名,但卻無法讓我的頭部得到子查詢的工作。我目前的代碼是 -

SELECT TOP 10 Orders.[Customer Name], 
       Sum(Orders.[Actual Revenue]) AS [SumOfActual Revenue], 
       Orders.[This Month], 
       Shop_Lookup.[ShopGroup] 

FROM Orders 
INNER JOIN Shop_Lookup ON Orders.[ShopID] = ShopLookup.[ShopID]  
WHERE ((Orders.[This Month])="current")  
GROUP BY Orders.[Customer Name], Orders.[This Month], Shop_Lookup.[ShopGroup]  
ORDER BY Sum(Orders.[Actual Revenue]) DESC; 
+0

好問題。如果你不能很快得到正確的答案,可以考慮添加最終結果的表示。 – Smandoli 2014-10-08 17:06:01

回答

1

完全AIR編碼!謹慎行事。

你可以使用子查詢來獲得這個!

SELECT 
    Orders.[Customer Name], 
    Sum(Orders.[Actual Revenue]) AS [SumOfActual Revenue], 
    Orders.[This Month], 
    Shop_Lookup.[ShopGroup] 
FROM 
    Orders 
    INNER JOIN 
    Shop_Lookup 
    ON 
    Orders.[ShopID] = ShopLookup.[ShopID]  
WHERE 
    (
     (Orders.[This Month] = 'Current') 
     AND 
     (Orders.ShopID IN 
      (SELECT 
       TOP 10 ShopID        
      FROM 
       Orders AS Dupe        
      WHERE 
       Dupe.ShopID = Orders.ShopID  
      ) 
     ) 
    ) 
GROUP BY 
    Orders.[Customer Name], 
    Orders.[This Month], 
    Shop_Lookup.[ShopGroup]  
ORDER BY 
    Sum(Orders.[Actual Revenue]) DESC; 

對子查詢的更多信息:http://allenbrowne.com/subquery-01.html

+0

我沒有測試這個,但它看起來不錯 - 我要走出去並且投票。 – Smandoli 2014-10-08 17:04:30

+0

謝謝@Smandoli,理論上它應該工作。但是,如果沒有測試,則無法確認。 :)感謝upvote! – PaulFrancis 2014-10-09 08:55:00