I have a table like this
userId story novel
1 a b
1 a b
1 a c
1 b c
1 b c
2 x x
2 x y
2 y y
3 m n
4 NULL NULL
How do I find the most story and novel count per user?
What I am looking for is the highest distinct count of story and novel for each user. So if a user has no story then story_count should be 0.
Desired output looks like this
userId story story_count novel novel_count
1 a 3 c 3
2 x 2 y 2
3 m 1 n 1
4 NULL 0 NULL 0
This is my faulty current attempt
SELECT userId, story, COUNT(story) as story_count, novel, COUNT(novel) as novel_count
FROM logs WHERE user = (SELECT DISTINCT(user)) GROUP BY story, novel;
4
Answers
I hope this works:
Based on Tim’s answer,I provide an upgrade solution
DB Fiddle Demo
You should really use a window function if this is possible because thus, you can keep your query much shorter and simpler. If this is not possible and you really need to do it without them, you can also create two subqueries for both the story data and the novel data according to your conditions and then join them. Something like this:
But as you can see, this will become very complicated although it will produce the correct outcome. See here:
db<>fiddle
Therefore, I once again highly recommend to use a DB version that provides window functions.
Try the following for MySQL 5.7:
This query will select all the equal highest counts of story and novel for each user, if you want to select only one highest count (from the multiple equal highest counts) then replace the if statement with this
if(@u<>userid, @rn:=1, @rn:= @rn+1) rnk
.See a demo.