Mysql ranking with upper and lower rankers - mysql

I want to get range ranking from a table using mysql query.
the table is like this,
+------------+------+
| first_name | age |
+------------+------+
| Kathy | 2 |
| Jane | 1 |
| Nick | 3 |
| Bob | 5 |
| Anne | 4 |
| Jack | 6 |
| Bill | 8 |
| Steve | 7 |
+------------+------+
and I want to get Jack's ranking with 2 lower and upper rankers.
+------------+------+
| Anne | 4 |
| Bob | 5 |
| Jack | 6 |
| Steve | 7 |
| Bill | 8 |
+------------+------+
Any idea how to write this query for a MySQL database?

Here is a very ugly way to do this by applying a rownumber to the records. By applying the rownumber to the records, then you you will be able to return rows if the ages are not consecutive (Demo with Non-consecutive ages):
select age, first_name
from
(
select t1.age, t1.first_name, #rownum:=#rownum+1 AS rownum
from yourtable t1, (SELECT #rownum:=0) r
order by t1.age
) x
where rownum >= (select rownum
from
(
select t.age,
t.first_name,
#rownum:=#rownum+1 AS rownum
from yourtable t, (SELECT #rownum:=0) r
order by t.age
) x
where first_name = 'jack') - 2
and rownum <= (select rownum
from
(
select t.age,
t.first_name,
#rownum:=#rownum+1 AS rownum
from yourtable t, (SELECT #rownum:=0) r
order by t.age
) x
where first_name = 'jack') + 2;
see SQL Fiddle with Demo

Working Example:
SELECT * FROM yourtable WHERE id BETWEEN ((SELECT id FROM yourtable WHERE name = 'Jack') - 2) AND ((SELECT id FROM yourtable WHERE name = 'Jack') + 2);
SQL Fiddle Demo

Related

Mysql Select and count rows with multiple same values

I am trying to create a query that allows me to select the data like shown below
id Counter_Type Champion_Name Counter_Lane
---|------------|------------|--------------
1 | 1 | Ahri | 1
2 | 1 | Ahri | 2
5 | 1 | Ahri | 2
3 | 1 | Ahri | 3
4 | 1 | Ahri | 2
6 | 1 | Teemo | 1
7 | 1 | Warwick | 4
8 | 1 | Warwick | 4
It should count the Counter_Lane and then the Counter_Type with the most should be shown for that name as shown below how it should show the data:
id Counter_Type Champion_Name Counter_Lane
---|------------|------------|--------------
1 | 1 | Ahri | 2
2 | 1 | Teemo | 1
3 | 1 | Warwick | 4
I have tried the following code and its the closest I have came for over 3 hours now, so could someone help please.
SELECT
a.Counter_Type, Champion_For, a.Counter_Lane, a.Champion_Name, COUNT(*) as Amount, sum(vote_type = 'up') as Upvotes, sum(vote_type = 'down') as Downvotes, sum(vote_type = 'up')-sum(vote_type = 'down') as Totalvotes
FROM Champion_Counters_Data a
JOIN ( SELECT c.Counter_Lane, c.Champion_Name, COUNT(*) magnitude
FROM Champion_Counters_Data c
WHERE
Champion_For = "Aatrox" AND Counter_Type = 1 GROUP BY Champion_Name, Counter_Lane ORDER BY magnitude) b ON a.Champion_Name = b.Champion_Name AND b.Counter_Lane = a.Counter_Lane
GROUP BY Champion_Name
SELECT * FROM your_table GROUP BY MAX(Counter_Lane)
This query is based on the output you want from the table you have given.
You will need many subqueries as MySQL doesn't allow windows function or CTE.
Rextester Demo
SELECT #rn := #rn + 1 as id,
t3.*
from
(select t1.*
FROM
(SELECT counter_type,
champion_name,
counter_lane,
count(*) AS cnt
FROM table53
GROUP BY champion_name,
counter_lane
) t1
INNER JOIN
(SELECT counter_type,
champion_name,
max(cnt) AS mcnt
FROM
(SELECT counter_type,
champion_name,
counter_lane,
count(*) AS cnt
FROM table53
GROUP BY champion_name,
counter_lane
) t
GROUP BY counter_type,
champion_name
) t2
ON t1.counter_type=t2.counter_type
AND t1.champion_name=t2.champion_name
AND t1.cnt=t2.mcnt
) t3
,(SELECT #rn := 0) t
;
Output
+-----+--------------+---------------+--------------+-----+
| id | counter_type | champion_name | counter_lane | cnt |
+-----+--------------+---------------+--------------+-----+
| 1 | 1 | Ahri | 2 | 3 |
| 2 | 1 | Teemo | 1 | 1 |
| 3 | 1 | Warwick | 4 | 2 |
+-----+--------------+---------------+--------------+-----+
Idea is to first group by champion_name and counter_lane and get the count . So for Ahri you will get cnt as 3. Now use another subquery to get corresponding counter_lane, which will be 2 for Ahri. At last, use a sequence number to generate id as 1,2,3 etc.
Try following SQL statement:
SELECT Counter_Type , Champion_Name, MAX(Counter_Lane) 'Counter_Lane'
FROM(
SELECT Counter_Type , Champion_Name , Counter_Lane
FROM Champion_Counters_Data
GROUP BY Counter_Type , Champion_Name
HAVING COUNT(Counter_Lane) >= 2
) tb
GROUP BY Counter_Type , Champion_Name

Select two items with maximum number of common values

I have the following table:
+----+-----------+-----------+
| id | teacherId | studentId |
+----+-----------+-----------+
| 1 | 1 | 4 |
| 2 | 1 | 2 |
| 3 | 1 | 1 |
| 4 | 1 | 3 |
| 5 | 2 | 2 |
| 6 | 2 | 1 |
| 7 | 2 | 3 |
| 8 | 3 | 9 |
| 9 | 3 | 6 |
| 10 | 1 | 6 |
+----+-----------+-----------+
I need a query to find two teacherId's with maximum number of common studentId's.
In this case teachers with teacherIds 1,2 have common students with studentIds 2, 1, 3, which is greater than 1,3 having common students 6.
Thanks in Advance!
[Edit]: After several hours I've had the following solution:
SELECT * FROM (
SELECT r1tid, r2tid, COUNT(r2tid) AS cnt
FROM (
SELECT r1.teacherId AS r1tid, r2.teacherId AS r2tid
FROM table r1
INNER JOIN table r2 ON r1.studentId=r2.studentId AND r1.teacherId!=r2.teacherId
ORDER BY r1tid
) t
GROUP BY r1tid, r2tid
ORDER BY cnt DESC
) t GROUP BY cnt ORDER BY cnt DESC LIMIT 1;
I was sure that there must exist more short and elegant solution, but I could not find it.
You would do this with a self-join. Assuming no duplicates in the table:
select t.teacherid, t2.teacherid, count(*) as NumStudentsInCommon
from table t join
table t2
on t.studentid = t2.studentid and
t.teacherid < t2.teacherid
group by t.teacherid, t2.teacherid
order by NumStudentsInCommon desc
limit 1;
If you had duplicates, you would just replace count(*) with count(distinct studentid), but count(distinct) requires a bit more work.
select t.teacherId, t2.teacherId, sum(t.studentId) as NumStudentsInCommon
from table1 t join
table1 t2
on t.studentId = t2.studentId and
t.teacherId < t2.teacherId
group by t.teacherId, t2.teacherId
order by NumStudentsInCommon desc

Specific Row in a Group with a Max Value

I have the following SQL SERVER table:
+--------+-------+-------+------+
| Person | Phone | Count | Rank |
+--------+-------+-------+------+
| A | X | 1 | 1 |
| B | X | 9 | 2 |
| C | X | 5 | 3 |
| T | Y | 6 | 1 |
| S | Y | 2 | 2 |
+--------+-------+-------+------+
I need the result to be the Person and Phone value where the Rank is equal to 1, but the MAX count value for the specific Phone for example:
+--------+-------+----------+------+
| Person | Phone | MaxCount | Rank |
+--------+-------+----------+------+
| A | X | 9 | 1 |
| T | Y | 6 | 1 |
+--------+-------+----------+------+
I can join on the table twice but was wondering if I can use MAX to achieve this?
You can use a subquery:
SELECT T.Person, T.Phone, (SELECT MAX(Count)
FROM YourTable AS TI
WHERE TI.Phone = T.Phone) AS MaxCount, T.[Rank]
FROM YourTable AS T
WHERE T.[RANK] = 1
SQL Fiddle
You can use MAX(Count)OVER(PARTITION BY Phone), for example with a CTE:
WITH CTE AS
(
SELECT Person,
Phone,
MaxCount = MAX(Count)OVER(PARTITION BY Phone),
Rank
FROM dbo.TableName
)
SELECT Person,
Phone,
MaxCount,
Rank
FROM CTE
WHERE Rank = 1
An alternative solution is to use outer apply like this:
SELECT Person,
Phone,
MaxCount,
[Rank]
FROM YourTable t1
OUTER APPLY (SELECT MAX([count]) AS MaxCount FROM YourTable WHERE Phone = t1.Phone) oa
WHERE [Rank] = 1

MySQL get ids of the range between two conditions

Let's say I've a table
+----+------------+
| id | condition |
+----+------------+
| 1 | open |
+----+------------+
| 2 | content |
+----+------------+
| 3 | content |
+----+------------+
| 4 | close |
+----+------------+
| 5 | nocontentx |
+----+------------+
| 6 | nocontenty |
+----+------------+
| 7 | open |
+----+------------+
| 8 | content |
+----+------------+
| 9 | close |
+----+------------+
| 10 | nocontentz |
+----+------------+
| 11 | open |
+----+------------+
| 12 | content |
+----+------------+
and want to get a new table where I get the IDs (the first and the last) of the values between "close" and "open". Note that the values between this two conditions are dynamic (I can't search by "nocontent"whatever)
Such as I get this table:
+----+----------+--------+
| id | start_id | end_id |
+----+----------+--------+
| 1 | 5 | 6 |
+----+----------+--------+
| 2 | 10 | 10 |
+----+----------+--------+
Thanks in advance!
http://sqlfiddle.com/#!2/c255c8/2
You can do this using a correlated subquery:
select (#rn := #rn + 1) as id,
id as startid,
(select id
from atable a2
where a2.id > a.id and
a2.condition = 'close'
order by a2.id asc
limit 1
) as end_id
from atable a cross join
(select #rn := 0) vars
where a.condition = 'open';
The working SQL Fiddle is here.
Note this returns the third open as well. If you don't want it, then add having end_id is not null to the end of the query.
EDIT:
If you know the ids are sequential, you can just add and subtract 1 from the above query:
select (#rn := #rn + 1) as id,
id+1 as startid,
(select id
from atable a2
where a2.id > a.id and
a2.condition = 'open'
order by a2.id asc
limit 1
) - 1 as end_id
from atable a cross join
(select #rn := 0) vars
where a.condition = 'close';
You can also do this in a different way, which is by counting the number of open and closes before any given row and using this as a group identifier. The way your data is structured, every other group is what you are looking for:
select grp, min(id), max(id)
from (select t.*,
(select sum(t2.condition in ('open', 'close'))
from t t2
where t2.id <= t.id
) as grp
from t
) t
where t.condition not in ('open', 'close') and
grp % 2 = 0
group by grp;

Limiting the output of specific column sql hana

I have a table structure as given below and what I'd like to be able to do is retrieve the top three records with the highest value for each Company code.
I've googled and I couldn't find a better way so hopefully you guys can help me out.
By the way, I'm attempting this in MySQL and SAP HANA. But I am hoping that I can grab the "structure" if the query for HANA if I can get help for only MySQL
Thanks much!
Here's the table:
http://pastebin.com/xgzCgpKL
In MySQL you can do
To get exactly three records per group (company) no matter ties emulating ROW_NUMBER() analytic function. Records with the same value get the same rank.
SELECT company, plant, value
FROM
(
SELECT company, plant, value, #n := IF(#g = company, #n + 1, 1) rnum, #g := company
FROM table1 CROSS JOIN (SELECT #n := 0, #g := NULL) i
ORDER BY company, value DESC, plant
) q
WHERE rnum <= 3;
Output:
| COMPANY | PLANT | VALUE |
|---------|-------|-------|
| 1 | C | 5 |
| 1 | B | 4 |
| 1 | A | 3 |
| 2 | G | 6 |
| 2 | C | 5 |
| 2 | D | 3 |
| 3 | E | 8 |
| 3 | A | 7 |
| 3 | B | 3 |
Get all records per group that have a rank from 1 to 3 emulating DENSE_RANK() analytic function
SELECT company, plant, value
FROM
(
SELECT company, plant, value, #n := IF(#g = company, IF(#v = value, #n, #n + 1), 1) rnum, #g := company, #v := value
FROM table1 CROSS JOIN (SELECT #n := 0, #g := NULL, #v := NULL) i
ORDER BY company, value DESC, plant
) q
WHERE rnum <= 3;
Output:
| COMPANY | PLANT | VALUE |
|---------|-------|-------|
| 1 | C | 5 |
| 1 | B | 4 |
| 1 | A | 3 |
| 1 | E | 3 |
| 1 | G | 3 |
| 2 | G | 6 |
| 2 | C | 5 |
| 2 | D | 3 |
| 3 | E | 8 |
| 3 | A | 7 |
| 3 | B | 3 |
| 3 | G | 3 |
Here is SQLFiddle demo
UPDATE: Now it looks like HANA supports analytic functions so the queries will look like
SELECT company, plant, value
FROM
(
SELECT company, plant, value,
ROW_NUMBER() OVER (PARTITION BY company ORDER BY value DESC) rnum
FROM table1
)
WHERE rnum <= 3;
SELECT company, plant, value
FROM
(
SELECT company, plant, value,
DENSE_RANK() OVER (PARTITION BY company ORDER BY value DESC) rank
FROM table1
)
WHERE rank <= 3;
Here is SQLFiddle demo It's for Oracle but I believe it will work for HANA too