MySQL : Get max values of groups - mysql

I have a table:
user_id | fav_song_genre | votes_as_fav_member
--------+----------------+--------------------
1 | hip hop | 3
2 | hip hop | 5
3 | rock | 8
4 | rock | 6
How do I get only results of user_id's with the highest votes_as_fav_member per group fav_song_genre:
Something like
SELECT *, MAX(votes_as_fav_member) as most_votes
FROM table
GROUP BY
fav_song_genre
I'm using that but it's not giving me the ID's of the members with most votes per genre.

This is not a problem of MySQL, rather a bit of logic problem with your approach.
Let's say we have the following:
user_id | fav_song_genre | votes_as_fav_member
--------+----------------+--------------------
1 | hip hop | 3
2 | hip hop | 5
3 | rock | 8
4 | rock | 6
5 | hip hop | 5
6 | rock | 8
Which ID should the query return? Should it return only one? or all that have the same amount of votes?
So, if you require only a single ID, what is the differentiation of a draw?
Lieven beat me to the SQL resolution by a few seconds, though.

Reasoning goes like
SELECT max vote for each genre
JOIN back with the original table to retrieve the additional columns for the records found.
SQL Statement
SELECT us.*
FROM UserSongs us
INNER JOIN (
SELECT fav_song_genre
, MAX(votes_as_fav_member) AS votes_as_fav_member
FROM UserSongs
GROUP BY
fav_song_genre
) usm ON usm.fav_song_genre = us.fav_song_genre
AND usm.votes_as_fav_member = us.votes_as_fav_member
Edit
How can I make sure the person with the lower ID is returned
SELECT MIN(us.user_id) as user_id
, us.fav_song_genre
, us.votes_as_fav_member
FROM UserSongs us
INNER JOIN (
SELECT fav_song_genre
, MAX(votes_as_fav_member) AS votes_as_fav_member
FROM UserSongs
GROUP BY
fav_song_genre
) usm ON usm.fav_song_genre = us.fav_song_genre
AND usm.votes_as_fav_member = us.votes_as_fav_member
GROUP BY
us.fav_song_genre
, votes_as_fav_member

Not sure if that's what you are asking:
SELECT g.fav_song_genre
, t.user_id
, g.most_votes
FROM yourTable t
JOIN
( SELECT fav_song_genre
, MAX(votes_as_fav_member) as most_votes
FROM yourTable
GROUP BY fav_song_genre
) AS g
ON t.fav_song_genre = g.fav_song_genre
AND t.votes_as_fav_member= g.most_votes
;

I created the table and tested, and I think this will also work
Table Data:
user_id fav_song_genre votes_as_fav_member
1 hip_hop 3
2 hip_hop 5
3 rock 8
4 rock 6
5 blues 20
6 indie 18
7 rock 35
8 country 33
9 hip_hop 35
10 indie 5
11 blues 7
12 hip_hop 59
13 indie 187
14 classic 45
15 country 61
16 hip_hop 243
Query:
select t.user_id, t.fav_song_genre, t.votes_as_fav_member
from (
select user_id, max(votes_as_fav_member) as max_votes, fav_song_genre
from table1 group by fav_song_genre
)
as x inner join table1 as t on t.votes_as_fav_member = x.max_votes and t.fav_song_genre = x.fav_song_genre;
Results:
user_id fav_song_genre votes_as_fav_member
5 blues 20
7 rock 35
13 indie 187
14 classic 45
15 country 61
16 hip_hop 243

Related

Getting wrong data from DB when joining MySql [duplicate]

I have a table of revenue as
title_id revenue cost
1 10 5
2 10 5
3 10 5
4 10 5
1 20 6
2 20 6
3 20 6
4 20 6
when i execute this query
SELECT SUM(revenue),SUM(cost)
FROM revenue
GROUP BY revenue.title_id
it produces result
title_id revenue cost
1 30 11
2 30 11
3 30 11
4 30 11
which is ok, now i want to combine sum result with another table which has structure like this
title_id interest
1 10
2 10
3 10
4 10
1 20
2 20
3 20
4 20
when i execute join with aggregate function like this
SELECT SUM(revenue),SUM(cost),SUM(interest)
FROM revenue
LEFT JOIN fund ON revenue.title_id = fund.title_id
GROUP BY revenue.title_id,fund.title_id
it double the result
title_id revenue cost interest
1 60 22 60
2 60 22 60
3 60 22 60
4 60 22 60
I can't understand why is it double it,please help
Its doubling because you have title repeated in fund and revenue tables. This multiplies the number of records where it matches. This is pretty easy to see if you remove the aggregate functions and look at the raw data. See here
The way to get around this is to create inline views of your aggregates and join on the those results.
SELECT R.title_id,
R.revenue,
R.cost,
F.interest
FROM (SELECT title_id,
Sum(revenue) revenue,
Sum(cost) cost
FROM revenue
GROUP BY revenue.title_id) r
LEFT JOIN (SELECT title_id,
Sum(interest) interest
FROM fund
GROUP BY title_id) f
ON r.title_id = F.title_id
output
| TITLE_ID | REVENUE | COST | INTEREST |
----------------------------------------
| 1 | 30 | 11 | 30 |
| 2 | 30 | 11 | 30 |
| 3 | 30 | 11 | 30 |
| 4 | 30 | 11 | 30 |
demo
The reason for this is that you have joined the table the first derived table from the second table without grouping it. To solve the problem, group the second table (fund) and join it with the first derived table using LEFT JOIN.
SELECT b.title_id,
b.TotalRevenue,
b.TotalCost,
d.TotalInterest
FROM
(
SELECT a.title_id,
SUM(a.revenue) TotalRevenue,
SUM(a.cost) TotalCost
FROM revenue a
GROUP BY a.title_id
) b LEFT JOIN
(
SELECT c.title_id,
SUM(a.interest) TotalInterest
FROM fund c
GROUP BY c.title_id
) d ON b.title_id = d.title_id
There are two rows for each title_id in revenue table.

Select one row where alert type and item id are the same and also how many similar rows

I am trying to make the notification system for my project as simple as possible on the user's side.
"john brown and 4 others liked your photo"
I tried:
Select a.id, a.item_id, a.type u.f_name, u.l_name, count(a)
From alerts
Join users on a.user_id = u.u_id
Where owner_id = {THE_USER_ID}
but it doesnt "work"
The users table
u_id | f_name | l_name
==========================
234 roy wright
654 pam brown
564 kim harris
334 tory plummer
876 rick forbes
123 paul nichol
980 mario chang
454 todd thompson
886 sam richards
215 tash gates
... ..... ........
The alerts table
id | item_id | type | user_id | owner_id
===================================================
1 21 like 234
2 21 comment 654
3 32 share 876
4 21 like 778
5 21 like 890
6 21 share 123
7 54 share 454
8 32 comment 655
9 60 comment 886
10 32 like 215
.. .. ...... ...
The results I want
id | item_id | type | u_id | f_name | l_name | amount_more
============================================================
1 21 like 234 roy wright 2
2 21 comment 654 pam brown
3 32 comment 876 rick forbes
6 21 share 123 paul nichol
7 54 share 454 todd thompson
9 60 comment 886 sam richards
10 32 like 215 tash gates
.. .. .... ... ..... ........
SELECT
MIN(CASE WHEN RowNumber = 1 THEN id END) as Id
,item_id
,type
,MIN(CASE WHEN RowNumber = 1 THEN u_id END) as u_id
,MIN(CASE WHEN RowNumber = 1 THEN f_name END) as f_name
,MIN(CASE WHEN RowNumber = 1 THEN l_name END) as l_name
,COUNT(*) - 1 as amount_more
FROM
(
SELECT
t.*
,(#rn:= if((#item = t.item_id) AND (#type = t.type),#rn + 1,
if((#item:=t.item_id) AND (#type:=t.type),1,1)
)
) as RowNumber
FROM
(SELECT *
FROM
alerts a
LEFT JOIN usersTbl u
ON a.user_id = u.u_id
WHERE
a.owner_id = 201
ORDER BY
a.item_id
,a.type
,a.id) t
CROSS JOIN (SELECT #rn:=0,#item:=0,#type:='') var
ORDER BY
item_id
,type
,id
) t2
GROUP BY
item_id
,type
ORDER BY
id
;
So you need to create a partitioned row number to identify which record you want to be considered first. Then using conditional aggregation you can choose that as your User. this works check it out here: http://rextester.com/VXZONO82847
In the Query you are not using aliases a and u properly, Use this:
Select
a.id,
a.item_id,
a.type,
u.f_name,
u.l_name,
count(a.*)
From alerts a Join users u
on(a.user_id = u.u_id)
Where owner_id = {THE_USER_ID}
group by 1,2,3,4,5;

Mysql SUM 0 when not in another table

I have 2 tables:
users:
id | name | club_id |
1 Bob 4
2 Jane 5
3 Alex 4
4 Paul 4
5 Tom 4
points:
user_id | club_id | amount(can vary)
1 4 10
1 2 10
2 5 10
3 4 10
3 4 10
4 4 10
3 2 10
3 4 10
I need (where users.club_id = 4 AND points.club_id = 4):
user_id | name | sum(amount)
3 Alex 30
1 Bob 10
4 Paul 10
5 Tom 0
Notice Tom is present in users but doesn't have any entries in points, so his sum should be 0. This is what throws me off in conjuction with grabbing a list from users.
Also would like this to be as efficient as possible (hence I added club_id = 4 both in users and points)
Try this:
SELECT
u.id,
u.name,
COALESCE(SUM(p.amount), 0) AS Totalpoints
FROM
(
SELECT *
FROM users
WHERE club_id = 4
) AS u
LEFT JOIN
(
SELECT *
FROM points
WHERE club_id = 4
) AS p ON p.user_id = u.id
GROUP BY u.id,
u.name;
See it in action here:
SQL Fiddle Demo
try this query
select u.id, u.name, sum(if (p.amount is null, 0, p.amount)) as totalPoint
from
user u
left join
(select * from point p where p.club_id = 4)p
on u.id = p.user_id
where u.club_id=4
group by u.id
SQL FIDDLE:

Getting Max date from multiple table after INNER JOIN

I have two following tables
table 1)
ID | HOTEL ID | NAME
1 100 xyz
2 101 pqr
3 102 abc
table 2)
ID | BOOKING ID | DEPARTURE DATE | AMOUNT
1 1 2013-04-12 100
2 1 2013-04-14 120
3 1 2013-04-9 90
4 2 2013-04-14 100
5 2 2013-04-18 150
6 3 2013-04-12 100
I want to get reault in mysql such that it take the row from table two with MAX DEPARTURE DATE.
ID | BOOKING ID | DEPARTURE DATE | AMOUNT
2 1 2013-04-14 120
5 2 2013-04-18 150
6 3 2013-04-12 100
SELECT b.ID,
b.BookingID,
a.Name,
b.departureDate,
b.Amount
FROM Table1 a
INNER JOIN Table2 b
ON a.ID = b.BookingID
INNER JOIN
(
SELECT BookingID, MAX(DepartureDate) Max_Date
FROM Table2
GROUP BY BookingID
) c ON b.BookingID = c.BookingID AND
b.DepartureDate = c.Max_date
SQLFiddle Demo
Well,
SELECT * FROM `table2` ORDER BY `DEPARTURE_DATE` DESC LIMIT 0,1
should help

Mysql join and sum is doubling result

I have a table of revenue as
title_id revenue cost
1 10 5
2 10 5
3 10 5
4 10 5
1 20 6
2 20 6
3 20 6
4 20 6
when i execute this query
SELECT SUM(revenue),SUM(cost)
FROM revenue
GROUP BY revenue.title_id
it produces result
title_id revenue cost
1 30 11
2 30 11
3 30 11
4 30 11
which is ok, now i want to combine sum result with another table which has structure like this
title_id interest
1 10
2 10
3 10
4 10
1 20
2 20
3 20
4 20
when i execute join with aggregate function like this
SELECT SUM(revenue),SUM(cost),SUM(interest)
FROM revenue
LEFT JOIN fund ON revenue.title_id = fund.title_id
GROUP BY revenue.title_id,fund.title_id
it double the result
title_id revenue cost interest
1 60 22 60
2 60 22 60
3 60 22 60
4 60 22 60
I can't understand why is it double it,please help
Its doubling because you have title repeated in fund and revenue tables. This multiplies the number of records where it matches. This is pretty easy to see if you remove the aggregate functions and look at the raw data. See here
The way to get around this is to create inline views of your aggregates and join on the those results.
SELECT R.title_id,
R.revenue,
R.cost,
F.interest
FROM (SELECT title_id,
Sum(revenue) revenue,
Sum(cost) cost
FROM revenue
GROUP BY revenue.title_id) r
LEFT JOIN (SELECT title_id,
Sum(interest) interest
FROM fund
GROUP BY title_id) f
ON r.title_id = F.title_id
output
| TITLE_ID | REVENUE | COST | INTEREST |
----------------------------------------
| 1 | 30 | 11 | 30 |
| 2 | 30 | 11 | 30 |
| 3 | 30 | 11 | 30 |
| 4 | 30 | 11 | 30 |
demo
The reason for this is that you have joined the table the first derived table from the second table without grouping it. To solve the problem, group the second table (fund) and join it with the first derived table using LEFT JOIN.
SELECT b.title_id,
b.TotalRevenue,
b.TotalCost,
d.TotalInterest
FROM
(
SELECT a.title_id,
SUM(a.revenue) TotalRevenue,
SUM(a.cost) TotalCost
FROM revenue a
GROUP BY a.title_id
) b LEFT JOIN
(
SELECT c.title_id,
SUM(a.interest) TotalInterest
FROM fund c
GROUP BY c.title_id
) d ON b.title_id = d.title_id
There are two rows for each title_id in revenue table.