lxndr Posted January 24, 2007 Share Posted January 24, 2007 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, iename: johnyear: 1958field x: etcfield y: etcname: johnyear: 1958field x: etcfield y: etc.. would only count once for the name "John" .. the output I'm looking for is:name occurrencesJohn 235Mary 167etcTo 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: 3but 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 https://forums.phpfreaks.com/topic/35570-need-help-with-distinct-or-another-approach/ Share on other sites More sharing options...
effigy Posted January 24, 2007 Share Posted January 24, 2007 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 https://forums.phpfreaks.com/topic/35570-need-help-with-distinct-or-another-approach/#findComment-168492 Share on other sites More sharing options...
fenway Posted January 24, 2007 Share Posted January 24, 2007 Derived tables are definitely the way to go. Link to comment https://forums.phpfreaks.com/topic/35570-need-help-with-distinct-or-another-approach/#findComment-168496 Share on other sites More sharing options...
lxndr Posted January 24, 2007 Author Share Posted January 24, 2007 [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 https://forums.phpfreaks.com/topic/35570-need-help-with-distinct-or-another-approach/#findComment-168509 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.