在SELECT语句中使用带有SUM的子查询

时间:2014-06-03 19:40:24

标签: ms-access-2010

以下是我的情景:

我将以下数据存储在表(CustomerSales)中:

CustomerCode   CustomerName   SalesAmt   Year
001            Customer 1     $10.00     2014
001            Customer 1     $15.00     2014
001            Customer 1     $5.00      2013
002            Customer 2     $5.00      2014
002            Customer 2     $5.00      2013

我想要一份报告,按年显示客户销售情况。示例期望的结果:

Customer Code   Customer Name   2013 Sales   2014 Sales
001             Customer 1      $5.00        $25.00
002             Customer 2      $5.00        $5.00

我当前的查询是返回所有客户的总年度金额,而不仅仅是该行。例如:

Customer Code   Customer Name   2013 Sales   2014 Sales
001             Customer 1      $10.00        $30.00
002             Customer 2      $10.00        $30.00

我目前的查询如下:

SELECT [CustomerSales].[CustomerCode], [CustomerSales].[CustomerName],
    (SELECT Sum([CustomerSales].[SalesAmt]) 
     FROM [CustomerSales] 
     WHERE [CustomerSales].[Year] = "2013") AS "2013 Sales",
    (SELECT Sum([CustomerSales].[SalesAmt]) 
     FROM [CustomerSales] 
     WHERE [CustomerSales].[Year] = "2014") AS "2014 Sales",
FROM [CustomerSales]
GROUP BY [CustomerSales].[CustomerCode], [CustomerSales].[CustomerName], [CustomerSales].[Year];

我正在使用Access 2010.任何帮助都会非常感谢!

注意:我确定这是一个简单的错误,但我现在已经退出SQL游戏一段时间>。<

1 个答案:

答案 0 :(得分:0)

不幸的是,我没有安装Access来测试我的查询。我在MySQL中编写了以下查询:

SELECT  CustomerSales.CustomerCode, 
        CustomerSales.CustomerName,
        SUM(IF(CustomerSales.Year='2013',CustomerSales.SalesAmt,0)) as "2013 Sales",
        SUM(IF(CustomerSales.Year='2014',CustomerSales.SalesAmt,0)) as "2014 Sales"
FROM CustomerSales
GROUP BY CustomerSales.CustomerCode, CustomerSales.CustomerName, CustomerSales.Year;

显然,Access有一个类似的IF构造IIF(http://office.microsoft.com/en-us/access-help/iif-function-HA001228853.aspx

因此,您应该假设能够重建您的查询:

SELECT  [CustomerSales].[CustomerCode], 
        [CustomerSales].[CustomerName],
    SUM(IIF([CustomerSales].[Year]='2013',[CustomerSales].[SalesAmt],0)) as "2013 Sales",
    SUM(IIF([CustomerSales].[Year]='2014',[CustomerSales].[SalesAmt],0)) as "2014 Sales"        
FROM [CustomerSales]
GROUP BY [CustomerSales].[CustomerCode], [CustomerSales].[CustomerName], [CustomerSales].[Year];

请告诉我这是否适合您:)