David Rodrigues
David Rodrigues

Reputation: 12542

Get how many users who responded to a survey

I need to know how many users who responded to a survey. But they can respond one or more times (in my case, two times max).

So I have two tables: fs_users and fs_surveys.

fs_users:
  ID  | Name
  1     David
  2     John

fs_surveys:
  ID  | ID_User | Selected_Answer
  1     1         A
  2     1         C
  3     2         A

If I count visually how many users who responded the survey, I can count 2 (David and John). By query, I can know who are this peoples that responded to. Like:

SELECT 
  fs_users.ID, 
  fs_users.Name
FROM fs_users

INNER JOIN fs_surveys
  ON fs_surveys.ID_User = fs_users.ID

GROUP BY 
  fs_users.ID

It basically will return the same of fs_users data represented above. So, until here I'm fine. The problem is that I need to COUNT() how many users, instead of, who users.

If I just change the SELECT to something like:

SELECT
  COUNT(*)
...

I will receive this:

result:
  COUNT(*) | INSTEAD_OF
  3          2

So, how I can solve this problem? Bye!

Upvotes: 2

Views: 101

Answers (4)

steffen
steffen

Reputation: 17018

Just use COUNT(DISTINCT fs_users.ID) for counting unique values.

Upvotes: 2

aF.
aF.

Reputation: 66707

Use COUNT(distinct columnName) instead of COUNT(*).

Upvotes: 4

Mike Brant
Mike Brant

Reputation: 71384

Just use DISTINCT:

SELECT COUNT(DISTINCT ID) FROM fs_users;

Upvotes: 4

eggyal
eggyal

Reputation: 125925

SELECT COUNT(DISTINCT ID_User) FROM fs_surveys

See it on sqlfiddle.

Upvotes: 6

Related Questions