使用Group By,Top N和Sum进行查询

时间:2014-10-08 10:29:26

标签: sql ms-access ms-access-2007

我浏览了论坛,可以找到各种各样的例子来解决我的问题,但是不能把所有东西放在一起。

我的情况是典型的,我希望按组(Shop_Lookup.ShopGroup)显示前十名客户(订单。[客户名称])的总收入。

到目前为止,无论ShopGroup如何,我都可以获得总体排名前10位,但却无法让我的头脑能够让Sub Query工作。我目前的代码是 -

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;

1 个答案:

答案 0 :(得分:1)

完全空气编码!谨慎行事。

您可以使用Sub Query来获取此信息!

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