简体   繁体   中英

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

I have two tables, with different column names, as follows:

Table Orders: Due Date, Pay, Exchange Rate

Table Invoices: Date, Subtotal, Exchange Rate

I'd like the following resulting table: Year, Month, Total

Where the two tables are UNIONED ALL on date + month and Total is the SUM of all rows in the two tables.

My pseudo-SQL looks like this:

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

I'm failing on the GROUP BY, for using ALIASES (error saying not using YEAR(ORDREC.[Due Date]) in an aggregate function), but I must use aliases as the column names are DIFFERENT in the two tables. Any suggestions on how to achieve this in a single SQL query?

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

When you use aggregate function you need to add non-aggregate columns in GROUP BY clause.

You use SUM aggregate function in your UNION ALL query, need to add non-aggregate columns in GROUP BY clause in the two query.

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

if I understand correctly, you can use this then do SUM aggregate function , I think the error will disappear.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM