1

I'm trying to add a column which calculates percentages of different products in MS Access Query. Basically, this is the structure of the query that I'm trying to reach:

Product | Total | Percentage
 Prod1    |   15    |    21.13%
 Prod2    |   23    |    32.39%   
 Prod3    |   33    |    46.48%   
Product |   71    |    100%


The formula for finding the percent I use is: ([Total Q of a Product]/[Totals of all Products])*100, but when I try to use the expression builder (since my SQL skills are basic) in MS Access to calculate it..

= [CountOfProcuts] / Sum([CountOfProducts])

..I receive an error message "Cannot have aggregate function in GROUP BY clause.. (and the expression goes here)". I also tried the option with two queries: one that calculates only the totals and another that use the first one to calculate the percentages, but the result was the same.

I'll be grateful if someone can help me with this.

Stiliyan Vasilev
  • 179
  • 2
  • 3
  • 14

1 Answers1

6

You can get all but the last row of your desired output with this query.

SELECT
    y.Product,
    y.Total,
    Format((y.Total/sub.SumOfTotal),'#.##%') AS Percentage
FROM
    YourTable AS y,
    (
        SELECT Sum(Total) AS SumOfTotal
        FROM YourTable
    ) AS sub;

Since that query does not include a JOIN or WHERE condition, it returns a cross join between the table and the single row of the subquery.

If you need the last row from your question example, you can UNION the query with another which returns the fabricated row you want. In this example, I used a custom Dual table which is designed to always contain one and only one row. But you could substitute another table or query which returns a single row.

SELECT
    y.Product,
    y.Total,
    Format((y.Total/sub.SumOfTotal),'#.##%') AS Percentage
FROM
    YourTable AS y,
    (
        SELECT Sum(Total) AS SumOfTotal
        FROM YourTable
    ) AS sub
UNION ALL
SELECT
    'Product',
    DSum('Total', 'YourTable'),
    '100%'
FROM Dual;
Community
  • 1
  • 1
HansUp
  • 95,961
  • 11
  • 77
  • 135
  • Ha. Well done. I was just about to post the same thing, except: **(1)** I was going to go all egghead and use the term "cartesian product", **(2)** I was going to leave the percentages as fractions, and **(3)** I was going to bail on the whole "final totals" row. My reasoning for (2) and (3) is that they should only be part of the *presentation* of the data (e.g. on a report), not the data itself. – Gord Thompson Oct 30 '13 at 21:28
  • 1
    Thanks. **(1)** I'm feeling a bit cross today. **(2)** and **(3)** Yeah, me too. But sometimes they still want what they want. :-) Answers are based on judgement calls and another time I might have answered differently ... perhaps even closer to the answer you didn't submit. – HansUp Oct 30 '13 at 21:34