get the most frequently appearing user_code where the month is specified
Just add a WHERE
clause:
SELECT user_code, COUNT(invite_code) AS counted
FROM invite_table
WHERE month = 'May' -- or whatever is stored in your varchar(3) column
GROUP BY user_code
ORDER BY counted DESC, user_code -- to break ties in deterministic fashion
LIMIT 10;
You would GROUP BY user_code
of course, not by invite_code
.
OTOH, since user_code
is the PK, the whole question is nonsense. There can never be more than one. Maybe you meant invite_code
after all? In this case, since the column can be NULL, also consider excluding NULL values:
SELECT invite_code, COUNT(*) AS counted
FROM invite_table
WHERE month = 'May' -- or whatever is stored in your varchar(3) column
AND invite_code IS NOT NULL -- exclude NULL
GROUP BY invite_code
ORDER BY counted DESC, invite_code -- to break ties in deterministic fashion
LIMIT 10;
A month column as varchar(3)
doesn't seem very useful if there can be data for more than a single year. I would use data type date
for it. You can format that any way you like for presentation. Like:
SELECT to_char(date '2017-12-01', 'Mon'); -- 'Dec'