每年的每日汇总计算

时间:2016-04-23 03:00:10

标签: sql ms-access subquery

以下ACCESS查询返回一系列年份的每日汇总金额。它运行时没有错误,但3列的结果都为零。如果有人能说出为什么没有正确添加总和,我将不胜感激。

SELECT     
     Month(days.day_start) AS [MONTH], 
     Day(days.day_start) AS [DAY],
     Year(days.day_start) AS [YEAR], 

     (SELECT Round(Nz(Sum(sales_receipt.SELLING_PRICE * sales_receipt.quantity),0) ,2)  
      FROM SALES_RECEIPT
      INNER JOIN INVENTORY ON INVENTORY.INVENTORY_ID = SALES_RECEIPT.INVENTORY_ID 
      WHERE SALES_RECEIPT.[SALE_DATE] >= days.day_start 
       AND SALES_RECEIPT.[SALE_DATE] < days.day_end) AS [Daily Sales Total],

     (SELECT Round(Nz(Sum(sales_receipt.SELLING_PRICE * sales_receipt.quantity),0) ,2) 
      FROM SALES_RECEIPT
      INNER JOIN INVENTORY ON INVENTORY.INVENTORY_ID = SALES_RECEIPT.INVENTORY_ID 
      WHERE SALES_RECEIPT.[SALE_DATE] >= days.day_start 
       AND SALES_RECEIPT.[SALE_DATE] < days.day_end  
       AND SALES_RECEIPT.SALES_TAX_EXEMPT="No") AS [Taxable Sales],

     (SELECT Round(Nz(Sum(sales_receipt.SELLING_PRICE * sales_receipt.quantity),0) ,2) 
     FROM SALES_RECEIPT
     INNER JOIN INVENTORY ON INVENTORY.INVENTORY_ID = SALES_RECEIPT.INVENTORY_ID 
     WHERE SALES_RECEIPT.[SALE_DATE] >= days.day_start 
       AND SALES_RECEIPT.[SALE_DATE] < days.day_end 
       AND SALES_RECEIPT.SALES_TAX_EXEMPT="Yes") AS [Tax Free Sales]

FROM    
   (SELECT 
         DateSerial(Year(sale_date), Month(sale_date), Day(sale_date)) AS day_start,
         DateAdd("s", -1, DateSerial(Year(sale_date), 
                 Month(sale_date), Day(sale_date))) AS day_end

    FROM SALES_RECEIPT
    WHERE sale_date >=  #1/1/2009# AND sale_date < #12/31/2016# 
    GROUP BY Year(sale_date), Month(sale_date), Day(sale_date) 
   ) AS days;

1 个答案:

答案 0 :(得分:0)

您的子查询聚合返回零,因为day_end小于day_start子查询&#39}。 WHERE子句假定日期范围相反。事实上,day_end子句派生表中指定的FROM 一秒小于sale_date

DateAdd("s", -1, DateSerial(Year(sale_date), 
                 Month(sale_date), Day(sale_date)) AS day_end

查看DateAdd's区间值并重新考虑您的需求。顺便说一句,DateSerial()在这里是多余的。以正间隔正确返回开始日期和结束日期之间的可行范围。以下是开始日期和结束日期之间的100天:

sale_date As day_start,
DateAdd("d", 100, sale_date) AS day_end