SQL Subquerys and RANK() - sql

I'm using below for a tournament system. The table contains registrered lengths for all teams. The result will be a scoreboard, summing up all teams length in a totalScore.
I'm trying to get the RANK() function into my SQL but I'm stuck right now. I want to get the current teams rank score out from my DB. Anyone got any ideas? I'm using MariaDB.
select team, sum(length) as totalScore
from
(SELECT t.*,
#num_in_group:=case when #team!=team then #num_in_group:=0 else #num_in_group:=#num_in_group+1 end as num_in_group,
#team:=team as t
FROM reg_catches t, (select #team:=-1, #num_in_group:=0) init
ORDER BY team asc, length desc) sub
WHERE sub.num_in_group<=4
GROUP BY team
ORDER BY totalScore DESC;
Table
team length
-----------
26 70
25 70
25 95
25 98
25 100
25 100
25 100
25 122
Current output
team totalScore
-- --
25 520
26 70
Wanted output
rank team totalScore
-- -- --
1 25 520
2 26 70

SET #row = 0;
SELECT #row:=#row + 1 rank, a.team, a.total_score
FROM(SELECT team, sum(r.length) as total_score FROM reg_catches r GROUP BY
r.team) a;
Try the above

Got this far now with above help from Dickson, problem now is that it seems that the rank is based on team ID instead of totalScore :O
SET #row = 0;
SELECT #row:=#row + 1 rank, team, sum(length) as totalScore
from
(SELECT t.*,
#num_in_group:=case when #team!=team then #num_in_group:=0 else #num_in_group:=#num_in_group+1 end as num_in_group,
#team:=team as t
FROM reg_catches t, (select #team:=-1, #num_in_group:=0) init
ORDER BY team asc, length desc) sub
WHERE sub.num_in_group<=4 and competition = "#COMPID" and disqualified = 0
GROUP BY team
ORDER BY totalScore DESC
Current output
rank team totalScore
1 28381 479
58 28468 439
20 28412 436
25 28419 432
14 28404 427
5 28388 421
Wanted would be
rank team totalScore
1 28381 479
2 28468 439
3 28412 436
4 28419 432
5 28404 427
6 28388 421
SQL Fiddle: http://sqlfiddle.com/#!9/107d98/2/1

Related

SQL JOIN return only the first match

I think this is a basic question, but I couldn’t figure it out. I am new to this so please bear with me.
I am analyzing players data from the FIFA game, and I want to get a table with the highest rating of each individual player and the earliest age when that happened.
This is an example of the data:
id
name
position
rating
age
1
James
RW
70
20
1
James
RW
71
21
2
Frank
CB
73
23
2
Frank
CB
73
24
3
Miles
CM
75
27
3
Miles
CM
74
28
This is what the query should return:
id
name
position
rating
age
1
James
RW
71
21
2
Frank
CB
73
23
3
Miles
CM
75
27
I thought I could first get the highest overall for each player, and then do a JOIN to get the age, but that gives the other years a player had the same highest rating.
id
name
position
rating
age
1
James
RW
71
21
2
Frank
CB
73
23
2
Frank
CB
73
24
3
Miles
CM
75
27
Thank you,
One approach uses ROW_NUMBER with QUALIFY:
SELECT *
FROM yourTable
WHERE true
QUALIFY ROW_NUMBER() OVER (PARTITION BY id ORDER BY rating DESC, age) = 1;
Try this one (could be a bit faster):
with mytable as (
select 1 as id, "James" as name, "RW" as position, 70 as rating, 20 as age union all
select 1, "James", "RW", 71, 21 union all
select 2, "Frank", "CB", 73, 23 union all
select 2, "Frank", "CB", 73, 24 union all
select 3, "Miles", "CM", 75, 27 union all
select 3, "Miles", "CM", 74, 28
)
select array_agg(t order by rating desc, age asc limit 1)[OFFSET(0)].*,
from mytable as t
group by t.id
Try this one too if you want. I think it's what you need.
select p1.id,
p1.name,
p1.pos,
max(p1.rating),
p1.age
from players p1
join (select name, min(age) min_age
from players
group by 1) p2 on p1.name = p2.name and p1.age = p2.min_age
group by p1.id, p1.name, p1.pos, p1.age

Access SQL Query Top 1 of Group

I am trying to write a query that selects the Top record in each Group of Data.
eg Below
Division
Team
Points
1
Liverpool
90
1
Manchester
88
2
Leeds
94
2
Arsenal
77
3
Bolton
66
3
Spurs
72
3
Derby
33
I want my query to return the team with highest number of points in each division:
Division
Team
Points
1
Liverpool
90
2
Leeds
94
3
Spurs
72
I thought this should be easy.
Any ideas?
Thanks
In MS Access, you can use:
select t.*
from t
where t.points = (select max(t2.points)
from t t2
where t2.division = t.division
);
If there are ties, then this returns all matching teams. If you want only one team even when there are ties:
select t.*
from t
where t.team = (select t2.team
from t t2
where t2.division = t.division
order by t2.points desc, t2.team
);

Max 3 values of every group

I sorted my data to something like this and now I want to get top 3 max person_occurence by every company but I couldn't figure out how to do it.
person_occurence company person_id
67 company_1 110
66 company_2 176
64 company_3 100
64 company_3 196
63 company_4 127
62 company_1 150
61 company_5 120
60 company_3 140
59 company_5 154
59 company_5 162
59 company_4 194
58 company_4 109
58 company_3 128
58 company_1 156
I used this query to get max of every company but can't get top 3 max person_occurence
SELECT max(agent_occurence), company FROM table GROUP BY company;
Use window functions:
select t.*
from (select t.*,
row_number() over (partition by company order by person_occurrence desc) as seqnum
from t
) t
where seqnum <= 3;
Now, this assumes that you want the top 3 regardless of ties -- that is, if 4 are tied with the same highest value, this returns three of them. Ties make things more difficult. You may want dense_rank() or rank() instead.
You can use correlated subquery :
SELECT t1.*
FROM table t1
WHERE t1.person_occurencee = (SELECT max(t2.person_occurence) FROM table t2 WHERE t1.company = t2.company);
If your DBMS supports analytical function then you can also do :
select t.*
from (select t.*,
rank() over (partition by company order by person_occurrence desc) as seq
from t
) t
where seq <= 3;

How to select rows based on condition

The following is the code snippet.
Just design purpose I have added.
Here The user will be assigned multiple group.
So I want to select the person details alone.
Here Person id 103 have two different persmission for the same Product.
But the higher permission only be selected for the person.
But if he is not assinged to multiple group, the default permission should be selected.
Sample data
ProdId PersonId GroupId Permission
10103 78 55 15
10103 99 33 15
10103 100 33 0
10103 103 33 15
10103 103 40 0
10103 112 33 15
Result data should be
ProdId PersonId Permission
10103 78 15
10103 99 15
10103 100 0
10103 103 15
10103 112 15
You should use ROW_NUMBER() :
SELECT * FROM (
SELECT t.*,
ROW_NUMBER() OVER(PARTITION BY t.prodid,t.personID ORDER BY t.permission DESC) as rnk
FROM YourTable t) s
WHERE s.rnk = 1
I assumed you want the highest number on permission by your example? If not, change the ORDER BY clause to what you want.
Right now it will select all columns, specify the ones you want.
If you are using Oracle, try the below query..
select * from (
select ProdID, PersonID, Permission, row_number() over (partition by PersonID order by Permission Desc) as column1 from table1)
where column1 = 1;

How to select 6 top records of each individual records at the database when selecting from all rows

Assume that i have the following table
CREATE TABLE #tblUsersPokemons (
RecordId int NOT NULL,
PokemonId int NOT NULL,
PokemonExp int NOT NULL,
PokemonLevel int NOT NULL,
UserId int NOT NULL
)
Now the below query works awesome as expected
select
SUM(cast(PokemonExp as bigint)) as TotalExp,
MAX(PokemonLevel) as MaxPokeLevel,
Count(PokemonId) as TotalPoke,
UserId
from #tblUsersPokemons
group by UserId
Here example result of such query
ToplamExp MaxPokeLevel TotalPoke UserId
----------- --------------- ----------- --------
29372294 101 4 1
1134696 98 1 2
1400 98 1 101
24534365 98 4 102
1400 98 1 1102
1400 98 1 1103
1400 98 1 2102
1400 98 1 2103
789220 98 7 2105
1468 98 1 3104
Now here my question comes
I want to limit counted PokemonIds. What i mean is i want to select maximum 6 of each same PokemonId records. And from these records top 6 ordered desc by PokemonExp should be counted in.
For example a user has the below records
From this table the query should take record id : 1,2,3,4,5,6,9 and not take 7,8 since top 6 records for PokemonId 1 taken
If I understand correctly, you want the aggregations on the top 6 rows for each user. You can do this easily using row_number():
select SUM(cast(PokemonExp as bigint)) as ToplamExp,
MAX(PokemonLevel) as MaxPokeLevel,
Count(PokemonId) as TotalPoke,UserId
from (select p.*,
row_number() over (partition by userid order by pokemanexp desc) as seqnum
from tblUsersPokemons p
) p
where seqnum <= 6
group by UserId;
EDIT:
I think you want to include PokemonId in the partition by clause:
select SUM(cast(PokemonExp as bigint)) as ToplamExp,
MAX(PokemonLevel) as MaxPokeLevel,
Count(PokemonId) as TotalPoke,UserId
from (select p.*,
row_number() over (partition by userid, PokemonId
order by pokemanexp desc) as seqnum
from tblUsersPokemons p
) p
where seqnum <= 6
group by UserId;