2

I am looking to create a query in Microsoft Access that when run will count the unique elements in a field and output these values as a percentage of the total number of elements.

For example if I had the table SampleTable with the following field of 8 elements:

LetterValue

z

x

x

x

y

x

z

y

I am looking for an output that returns the following

LetterValue Percent

x 50%

y 25%

z 25%

Even better, is it possible to modify this simple count query to get this result?

SELECT LetterValue, COUNT(*) AS QTY
FROM SampleTable
GROUP BY LetterValue;
3
  • 1
    Well, you have the count for each letter value...so get the total number of letters, and you essentially have the percentages.
    – user554546
    Jul 1, 2013 at 17:22
  • Sadly, I do not know how to do this in MS Access, but the function you're looking for is pivot. Maybe that helps
    – Simon
    Jul 1, 2013 at 17:36
  • Yeah, that makes sense, but unfortunately I was specifically told to output the percentages in the query.
    – Calle
    Jul 1, 2013 at 17:39

2 Answers 2

4

There are several parts to this question, including converting the value to a string (so you can append a '%'):

SELECT st.LetterValue, cdbl(100.0*COUNT(*)/tot.tot)&'%' AS QTY
FROM SampleTable st,
     (select COUNT(*) as tot
      from SampleTable
     ) as tot
GROUP BY st.LetterValue, tot.tot;
3
  • This works, but the problem is that while my example has 8 values, the table which I will apply this to has over 1000000 values, is there a way I can do this without imputing the table values every time I run it?
    – Calle
    Jul 1, 2013 at 17:59
  • @Calle This query isn't specific to your problem, it would work if you had 2 values or a million values. But Gordon, maybe your typo is confusing him. tot.to Is probably asking him to enter a parameter. It should be tot.tot.
    – Scotch
    Jul 1, 2013 at 18:03
  • And now it works just fine, of course I need to change the sig figs, but that's easy. Thanks for your help.
    – Calle
    Jul 1, 2013 at 18:12
3

You could do something like this also

SELECT group_counts.letter, group_counts.countNums, (group_counts.countNums/total_count.total_nums*100) AS [Percent]
  FROM (SELECT letter, Count(*) AS countNums FROM [yourTable] GROUP BY letter) AS group_counts, 
       (SELECT Count(*) AS total_nums FROM [yourTable]) AS total_count;

This will output like

Letter     CountNums     Percent
 a         2             20
 b         4             40
 c         2             20
 d         1             10
 e         1             10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.