具有不同列名称的表上具有GROUP BY的Excel VBA SQL UNION SUM

时间:2018-08-13 15:46:54

标签: sql excel-vba group-by union-all

我有两个具有不同列名的表,如下所示:

表顺序: 到期日,付款,汇率

表格发票: 日期,小计,汇率

我想要以下结果表: 年,月,总数

两个表在日期和月份上是UNIONED ALL,而Total是两个表中所有行的总和。

我的伪SQL看起来像这样:

 public void onCellEdit(CellEditEvent event) {
        System.out.println("Cell Edit");
        brouillards.forEach(System.out::println);
        calculSolde();
//        Ajax.update("saisie:brouiDtable");
    }

    public void calculSolde() {
        totCredit = brouillards.stream().mapToDouble(Brouillard::getCredit).sum();
        totDebit = brouillards.stream().mapToDouble(Brouillard::getDebit).sum();
        if (totCredit >= totDebit) {
            soldeCredit = totCredit - totDebit;
            soldeDebit = 0D;
        } else {
            soldeDebit = totDebit - totCredit;
            soldeCredit = 0D;
        }
    }

我在GROUP BY上失败,因为使用了ALIASES(错误说在聚合函数中不使用YEAR(ORDREC。[到期日])),但是我必须使用别名,因为两个表中的列名不同。关于如何在单个SQL查询中实现此目标的任何建议?

Windows 10上的Excel 2016 Provider = Microsoft.Jet.OLEDB.4.0;

1 个答案:

答案 0 :(得分:0)

使用聚合函数时,需要在GROUP BY子句中添加非聚合列。

您在SUM查询中使用UNION ALL聚合函数,需要在两个查询的GROUP BY子句中添加非聚合列。

SELECT YearID, MonthID, SUM(Amount) FROM (

  SELECT YEAR(ORDREC.[Due Date]) as YearID, MONTH(ORDREC.[Due Date]) as MonthID, SUM(ORDREC.[Pay] * ORDREC.[Exchange Rate]) as Amount
  FROM orders-table AS ORDREC
  WHERE ...
  GROUP BY YEAR(ORDREC.[Due Date]),MONTH(ORDREC.[Due Date])
  UNION ALL

  SELECT YEAR(INV.[Date]) as YearID, MONTH(INV.[Date]) as MonthID, SUM(INV.[Subtotal] * INV.[Exchange Rate]) as Amount
  FROM invoices-table AS INV
  WHERE ...
  GROUP BY YEAR(INV.[Date]),MONTH(INV.[Date])

) x GROUP BY YearID, MonthID

如果我理解正确,则可以使用此功能,然后执行SUM 聚合函数,我认为错误将会消失。

SELECT YearID, MonthID, SUM(Amount) FROM (
  SELECT YEAR(ORDREC.[Due Date]) as YearID, MONTH(ORDREC.[Due Date]) as MonthID, (ORDREC.[Pay] * ORDREC.[Exchange Rate]) as Amount
  FROM orders-table AS ORDREC
  WHERE ...
  UNION ALL
  SELECT YEAR(INV.[Date]) as YearID, MONTH(INV.[Date]) as MonthID, (INV.[Subtotal] * INV.[Exchange Rate]) as Amount
  FROM invoices-table AS INV
  WHERE ...

) x GROUP BY YearID, MonthID