合并行SQL - Access

时间:2013-09-24 12:50:31

标签: sql ms-access

我在MS Access上有这个表:

Name | Week   | Manager | Sales
John | 201409 | Marcelo | 53
John | 201410 | Marcelo | 20
John | 201410 | Raquel  | 30
John | 201411 | Raquel  | 53

我必须通过最大销售额合并201410周并选择哪个经理。在此之后,我想总结这两个的总销售额,并这样做:

Name | Week   | Manager | Sales
John | 201409 | Marcelo | 53
John | 201410 | Raquel  | 50
John | 201411 | Raquel  | 53

有人能帮帮我吗?我尝试了很多SQL并且无能为力。

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

SELECT [Name], [Week], [Manager], SUM([Sales]) as Sales1
From [YourTable]
GROUP BY [Name], [Week], [Manager]

我没有测试过,所以让我知道你得到的错误。

答案 1 :(得分:0)

如果每一行都有一个唯一标识符(主键),那么它就会简单得多。但是,您使用的是您拥有的数据,而不是您希望拥有的数据,因此这是我完成它的迂回方式。您可以将此全部组合到一个查询中,并避免使用临时表;我把它拆分出来以方便理解,而不是简洁。

首先,提取每个名称 - 周组合的最高销售额:

SELECT Name, Week, MAX(Sales)
INTO #MaxSales
FROM [YourTable]
GROUP BY Name, Week

使用此信息获取您应该每周使用的经理(我们使用TOP 1来解决两位经理在同一名称/周内具有相同销售额的情况;我不确定您希望如何解决这个问题。):

SELECT Name, Week, Manager
INTO #MaxSalesManager
FROM [YourTable]
INNER JOIN #MaxSales
ON [YourTable].Name = #MaxSales.Name
AND [YourTable].Week = #MaxSales.Week
WHERE [YourTable].Sales = #MaxSales.Sales

现在您可以提取所需的信息:

SELECT [YourTable].Name, [YourTable].Week, #MaxSalesManager.Manager, SUM([YourTable].Sales)
FROM [YourTable]
INNER JOIN #MaxSalesManager
ON [YourTable].Name = #MaxSalesManager.Name
AND [YourTable].Week = #MaxSalesManager.Week
GROUP BY [YourTable].Name, [YourTable].Week, #MaxSalesManager.Manager

希望这有帮助!

修改

将它们全部合并到一个查询中:

SELECT [YourTable].Name, 
       [YourTable].Week, 
       #MaxSalesManager.Manager, 
       SUM([YourTable].Sales)
FROM [YourTable]
INNER JOIN 
    (SELECT Name, Week, Manager
    FROM [YourTable]
    INNER JOIN 
        (SELECT Name, Week, MAX(Sales)
        FROM [YourTable]
        GROUP BY Name, Week) AS #MaxSales
    ON [YourTable].Name = #MaxSales.Name
    AND [YourTable].Week = #MaxSales.Week
    WHERE [YourTable].Sales = #MaxSales.Sales) AS #MaxSalesManager
ON [YourTable].Name = #MaxSalesManager.Name
AND [YourTable].Week = #MaxSalesManager.Week
GROUP BY [YourTable].Name, [YourTable].Week, #MaxSalesManager.Manager