Excel VBA SQL 对具有不同列名的表进行 UNION SUM 和 GROUP BY

Excel VBA SQL UNION SUM with GROUP BY on Tables with Different Column Names

我有两个table,列名不同,如下:

Table 订单: 到期日、付款、汇率

Table 发票: 日期、小计、汇率

我想要以下结果 table: 年月总计

其中两个 table 是日期 + 月份的 UNIONED ALL,Total 是两个 table 中所有行的总和。

我的伪SQL长这样:

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 ...

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 ...

) x GROUP BY YearID, MonthID

我在 GROUP BY 上失败了,因为使用了 ALIASES(错误说没有在聚合函数中使用 YEAR(ORDREC.[Due Date])),但我必须使用别名,因为列名在两个 table。关于如何在单个 SQL 查询中实现此目的的任何建议?

Excel 2016 年 Windows 10 供应商=Microsoft.Jet.OLEDB.4.0;

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

您在UNION ALL查询中使用了SUM聚合函数,需要在两个查询的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