SQL查询老化报告

时间:2017-02-04 19:22:22

标签: mysql sql sql-server left-join datediff

我创建了一个SQL查询,该查询应该生成一个老化报告(根据未付天数显示未结余额并根据它们应该放入的老化桶进行分类)。查询如下:

SELECT (case when a.DaysOutstanding between 0 and 15 then 'AR_15'
             when a.DaysOutstanding between 16 and 30 then 'AR_15'
             when a.DaysOutstanding between 31 and 60 then 'AR_60'
             else 'AR_61'
        end)
FROM (SELECT RECEIPTS.CUST_No, sum(SALES.INV_AMT - RECEIPT.REC_AMT) as bal
      FROM RECEIPTS, SALES
      GROUP BY RECEIPTS.CUST_No
      ) b left outer join
     (SELECT RECEIPTS.CUST_No, MAX(RECEIPTS.REC_DATE) as LastPayDate,
      datediff(d, SALES.INV_DATE, getdate()) as DaysOutstanding
      FROM RECEIPTS, SALES
      GROUP BY RECEIPTS.CUST_No
      ) a on b.CUST_No = b.CUST_No
GROUP BY (case when a.DaysOutstanding between 0 and 15 then 'AR_15'
             when a.DaysOutstanding between 16 and 30 then 'AR_15'
             when a.DaysOutstanding between 31 and 60 then 'AR_60'
             else 'AR_61'
          end)
HAVING sum(SALES.INV_AMT - RECEIPT.REC_AMT) > 0

查询应过滤掉已完全支付的发票(= 0)。我相信HAVING子句中的某些内容以及代码的datediff行存在错误。

我是否可以使用错误或缺少某些内容来正确创建查询?

谢谢!

0 个答案:

没有答案