Jump to content

Need help with DISTINCT or another approach ??


lxndr

Recommended Posts

I'm trying to get a count of users in a particular table but I only want to count them once for each occurrence of another field in the database, ie

name: john
year: 1958
field x: etc
field y:  etc

name: john
year: 1958
field x: etc
field y: etc

.. would only count once for the name "John" .. the output I'm looking for is:

name  occurrences
John    235
Mary    167

etc

To try and make it clearer if John appears in the name column 10 times, 3 of those have the year column yet to 1958, 4 have 1960 and 3 have 1962 then I would want to return:

John:  3

but I need to do it for all the names in the one query.


I can see how I could use DISTINCT on the year field but how do I manage to get the user count based on it ?  Or is there a better way of doing this ?



Link to comment
Share on other sites

There may be a better way, but try this:
[s][tt]
SELECT name, COUNT(*) AS occurrences FROM (SELECT COUNT(*), name FROM [i][color=red]table[/color][/i] GROUP BY name, year) AS tmp GROUP BY name;
[/tt][/s]
[tt]
SELECT name, COUNT(*) AS occurrences FROM (SELECT DISTINCT name, year FROM [i][color=red]table[/color][/i]) AS tmp GROUP BY name;
[/tt]
Link to comment
Share on other sites

[quote author=effigy link=topic=123886.msg512712#msg512712 date=1169675182]
There may be a better way, but try this:
[s][tt]
SELECT name, COUNT(*) AS occurrences FROM (SELECT COUNT(*), name FROM [i][color=red]table[/color][/i] GROUP BY name, year) AS tmp GROUP BY name;
[/tt][/s]
[tt]
SELECT name, COUNT(*) AS occurrences FROM (SELECT DISTINCT name, year FROM [i][color=red]table[/color][/i]) AS tmp GROUP BY name;
[/tt]
[/quote]

Thanks heaps, that seems to be working great.  Appreciate the help.

..
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.