求和的SQL查询条件

时间:2014-07-01 00:47:52

标签: sql

我是SQL的新手,我对数据的显示以及如何让查询显示我想要的方式有疑问。我们的商务智能人员正在忙于其他项目,所以我们(财务)留下来收拾残局。如果相关的话,我将把它转储到ODBC到EXCEL中。

我的查询正在选择正确的信息,但我想要SUM (INVOICE.INVAMT)的两列,我希望INVOICE.INVAMT小于INVOICE.INVDATE的列为FUNDEPTPER.STARTDATE(或NULL) INVOICE.INVAMT以及当INVOICE.INVDATE介于FUNDEPTPER.STARTDATEFUNDDEPTPER.STOPDATE之间时SELECT FUNDERS.CODE, BILLBATCH.BATCH_ID, BILLBATCH.BATCHNO, SUM (INVOICE.INVAMT) AS [TOTAL CURRENT] FROM FUNDERS INNER JOIN ORDERS ON FUNDERS.FUNDER_ID= ORDERS.FUNDER_ID INNER JOIN INVOICE ON ORDERS.ORDER_ID=INVOICE.ORDER_ID INNER JOIN FUNDEPTPER ON FUNDEPTPER.PERIOD_ID = INVOICE.PERIOD_ID INNER JOIN BILLBATCH ON BILLBATCH.BATCH_ID= FUNDEPTPER.BATCH_ID WHERE BILLBATCH.BATCHNO = '?' AND INVOICE.INVTYPE='Invoice' AND INVOICE.INVDATE BETWEEN FUNDEPTPER.STARTDATE AND FUNDEPTPER.STOPDATE GROUP BY FUNDERS.CODE, BILLBATCH.BATCH_ID, BILLBATCH.BATCHNO 之和的列,(OR NULL)。总计也很不错。

我可以一次做一个,但不能同时做到 - 我的直觉说这可以做到 - 但我无法弄明白。

非常感谢您的帮助。我不需要具体了解(即确切的查询语言),如果你甚至可以解释高级别我可能得到它(如果可能的话)?

如果您需要我的查询:

{{1}}

2 个答案:

答案 0 :(得分:3)

您可以使用条件聚合

执行此操作
SELECT f.CODE, bb.BATCH_ID, bb.BATCHNO,
      SUM(i.INVAMT) AS TotalTotal,
      SUM(case when i.INVDATE BETWEEN fp.STARTDATE AND fp.STOPDATE then i.invamt else 0
          end) as TotalCurrent
      SUM(case when i.INVDATE < fp.STARTDATE Athen i.invamt else 0
          end) as TotalBefore
FROM FUNDERS f INNER JOIN
     ORDERS o
     ON f.FUNDER_ID = o.FUNDER_ID  INNER JOIN
     INVOICE i
     ON o.ORDER_ID = i.ORDER_ID INNER JOIN
     FUNDEPTPER fp
     ON fp.PERIOD_ID = i.PERIOD_ID INNER JOIN
     BILLBATCH bb
     ON bb.BATCH_ID= fp.BATCH_ID    
WHERE bb.BATCHNO = '?' AND i.INVTYPE = 'Invoice' 
GROUP BY f.CODE, bb.BATCH_ID, bb.BATCHNO;

此查询还引入了表别名。这些使查询更容易编写和阅读。

答案 1 :(得分:0)

我需要打破你理解你的询问的需要。

您需要 - SUM(INVOICE.INVAMT)的两列:

  1. 当INVOICE.INVDATE小于FUNDEPTPER.STARTDATE时,INVOICE.INVAMT(或NULL)的总和

    SELECT sum(invoice.invamt) FROM funders INNER JOIN ORDERS ON FUNDERS.FUNDER_ID= ORDERS.FUNDER_ID INNER JOIN INVOICE ON ORDERS.ORDER_ID=INVOICE.ORDER_ID INNER JOIN FUNDEPTPER ON FUNDEPTPER.PERIOD_ID = INVOICE.PERIOD_ID WHERE INVOICE.INVDATE < FUNDEPTPER.STARTDATE;

  2. INVOICE.INVDATE为INVOICE.INVAMT的总和  介于FUNDEPTPER.STARTDATE和FUNDDEPTPER.STOPDATE之间和之间

    SELECT sum(invoice.invamt) FROM funders INNER JOIN ORDERS ON FUNDERS.FUNDER_ID= ORDERS.FUNDER_ID INNER JOIN INVOICE ON ORDERS.ORDER_ID=INVOICE.ORDER_ID INNER JOIN FUNDEPTPER ON FUNDEPTPER.PERIOD_ID = INVOICE.PERIOD_ID WHERE INVOICE.INVDATE between FUNDERTPER.STARTDATE and FUNDDERTPER.STOPDATE