简体   繁体   中英

Two aggregate functions in MS Access SQL?

SELECT c.Category, SUM(c.[Market Value]), SUM([p.Market Value])
FROM Dec AS c, [NOV] as p
GROUP BY c.Category
;

Tells me the category is not part of the aggregate function. I just want to see the sums of each category for both tables. I do not want only certain values to appear so should I use Join?

EDIT:

SELECT c.[Category],  SUM(c.[Market Value]), SUM(p.[Market Value])
FROM Dec AS c
INNER JOIN Nov AS p ON c.ID = p.ID
GROUP BY c.category, p.Category
;

This is what I wrote using JOIN, it just runs the query for nonstop. Do I just wait? There are 80,000 rows of data, but doing one SUM grouped by category for just one month returns it instantly, why is it so hard to do two tables?

You need to UNION ALL your data:

SELECT Category, [market Value]
FROM DEC
UNION ALL 
SELECT Category, [market Value]
FROM NOV

When you run this query you will get the combined data for two months. If you want to get the sum for the combined data the just use the query:

SELECT Category, SUM([market Value]) as sum_value
FROM (
SELECT Category, [market Value]
FROM DEC
UNION ALL 
SELECT Category, [market Value]
FROM NOV
) as A
GROUP BY Category

Now, this is not what you want. You want two columns: one for Nov, one for Dec. To do this you need to slightly modify the UNION ALL query:

SELECT Category, [market Value], 'Dec' as type
FROM DEC
UNION ALL 
SELECT Category, [market Value], 'Nov' as type
FROM NOV

And the final query will be:

SELECT Category, 
SUM(iif(type='Dec', [Market Value], 0)) as Dec_Value, 
SUM(iif(type='Nov', [Market Value], 0)) as Nov_Value
FROM (
SELECT Category, [market Value], 'Dec' as type
FROM DEC
UNION ALL 
SELECT Category, [market Value], 'Nov' as type
FROM NOV
) as A
GROUP BY Category

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