MySQL: Select last x items of each user - mysql

I have a table with lots of timestamped entries for each user in my system:
id (int, PK)
user_id (int, FK)
date (datetime)
description (text)
other columns...
How do I select the last x (e.g. 2) items of each user?
(By last items, I mean of course items sorted desc by date)

Have a correlated sub-query to find a user_id's "second last" date:
select t1.*
from tablename t1
where t1.date >= (select date from tablename t2
where t2.user_id = t1.user_id
order by date desc
limit 1,1)
If you want 3 last rows for each user, adjust to LIMIT 2,1.

Try this:
SELECT t.id, t.user_id, t.`date`, t.`description`
FROM (SELECT id, user_id, `date`, `description`
FROM mytable t1
ORDER BY t1.date desc
LIMIT X) t --Change x to the number which you want.
GROUP BY t.id, t.user_id, t.`date`, t.`description`

Give a row number based on user_id order by descending order of date. Then select the rows having row number 1 and 2.
Query
select t1.id, t1.user_id, t1.`date`, t1.`description` from
(
select id, user_id, `date`, `description`,
(
case user_id when #curA
then #curRow := #curRow + 1
else #curRow := 1 and #curA := user_id end
) as rn
from ypur_table_name t,
(select #curRow := 0, #curA := '') r
order by user_id, `date` desc
)t1
where t1.rn in (1, 2); -- or change t1.rn <= 2. Change 2 accordingly

You can use below query-
SELECT x.*
FROM (SELECT t.*,
CASE
WHEN #category != t.user_id THEN #rownum := 1
ELSE #rownum := #rownum + 1
END AS rank,
#category := t.user_id AS var_category
FROM your_table AS t
JOIN (SELECT #rownum := NULL, #category := '') r
ORDER BY t.user_id,t.date DESC,t.id) x
WHERE x.rank<=2;
Note: x.rank<=2, put here how many rows you need user wise.

Related

What would the equivalent statement be in MySQL 5.6.39?

I recently moved to a shared host that has MySQL 5.6.39 instead of MariaDB 10.x, I was wondering what would the equivalent of the following MariaDB statement in MySQL?
SELECT rank,
total
FROM
(SELECT ROW_NUMBER() OVER (
ORDER BY `prestige` DESC, `xp` DESC) AS rank,
(SELECT COUNT(*)
FROM Modular_LS) AS total,
steamid
FROM Modular_LS) sub
WHERE sub.steamid = '%s'
I got as far as this, but now I'm stuck
SELECT rank, total FROM
(SELECT #rank := #rank +1 as rank FROM Modular_LS,
(SELECT COUNT(*) FROM Modular_LS) AS total, steamid FROM Modular_LS) sub,
(SELECT #rank := 0) r ORDER BY `prestige` DESC, `xp` DESC) t;
The table structure contains the column steamid, xp, prestige
My goal is to order by prestige descending first and then xp descending to put it in a ranking like-order, then using WHERE query to find a specific player's ranking. The output of which contains the rank (position) and the total (total amount of records)
Maybe this will get you started:
SELECT #rank := IF(player_id = #prev, #rank + 1, 1), #prev := player_id
FROM ( SELECT #rank := 1, #prev = 0 ) AS init
JOIN ( SELECT player_id
FROM Modular_LS
ORDER BY prestige DESC, SP DESC
) AS x ;
After a few hours, this is what I came up with that solved my problem.
SELECT
sub.rank
,sub.total
FROM
(
SELECT
t.id
,t.steamid
,#rownum : = #rownum + 1 AS rank
,(
SELECT
COUNT (*)
FROM
Modular_LS
) AS total
FROM
Modular_LS t JOIN (
SELECT
#rownum : = 0
) r
ORDER BY
t.prestige DESC
,t.xp DESC
) sub
WHERE
sub.steamid = '%s'

mysql query to get the average from the latest N rows for distinct phone_numbers

My table is (phone_number, bpm, timestamp). I want to get the phone_number, avg(bpm) for the latest 10 rows for each phone_number. I have tried..
SELECT phone_number, AVG( bpm )
FROM (
SELECT *
FROM table_name
WHERE bpm !=0
ORDER BY timestamp DESC
) AS temp
GROUP BY phone_number
HAVING COUNT( * ) <=10
This query is giving empty result. I cannot use IN clause in my version of mysql.
This is a pain in MySQL. The most reasonable solution uses variables to enumerate the rows and then aggregation:
SELECT phone_number, AVG(bpm)
FROM (SELECT t.*,
(#rn := if(#pn = phone_number, #rn + 1,
if(#pn := phone_number, 1, 1)
)
) as rn
FROM table_name t CROSS JOIN
(SELECT #pn := '', #rn := 0) params
WHERE bpm <> 0
ORDER BY phone_number, timestamp DESC
) t
WHERE rn <= 10
GROUP BY phone_number;

How to select certain numbers of groups in MySQL?

I have the table with data:
And for this table I need to create pegination by productId column. I know about LIMIT N,M, but it works with rows and not with groups. For examle for my table with pegination = 2 I expect to retrieve all 9 records with productId = 1 and 2 (the number of groups is 2).
So how to create pegination by numbers of groups ?
I will be very thankfull for answers with example.
One way to do pagination by groups is to assign a product sequence to the query. Using variables, this requires a subquery:
select t.*
from (select t.*,
(#rn := if(#p = productid, #rn + 1,
if(#rn := productid, 1, 1)
)
) as rn
from table t cross join
(select #rn := 0, #p := -1) vars
order by t.productid
) t
where rn between X and Y;
With an index on t(productid), you can also do this with a subquery. The condition can then go in a having clause:
select t.*,
(select count(distinct productid)
from t t2
where t2.productid <= t.productid)
) as pno
from t
having pno between X and Y;
Try this:
select * from
(select * from <your table> where <your condition> group by <with your group>)
LIMIT number;

To display top 4 rows using mysql Rank is displaying wrong

I need to display the top4 and lease 4 rows based Amount and group by agentId but here rank is showing wrong
And how to show least(last 4 rows?)
schema:
AgentID amount
1 3000
1 3200
2 9000
SELECT Agentid,SUM(AmountRecevied) as Amount,#rownum := #rownum + 1 AS Rank
FROM collection ,(SELECT #rownum := 0) r
GROUP BY AgentID
ORDER BY Amount DESC
limit 4;
Try this way:
SELECT T.Agentid,T.Amount, #rownum := #rownum - 1 AS Rank
FROM
(SELECT Agentid,SUM(AmountRecevied) as Amount
FROM collection
GROUP BY AgentID
ORDER BY Amount
LIMIT 4) T,(SELECT #rownum := 11) r
Try this :
SELECT
C.*,
#rownum := #rownum + 1 AS Rank
FROM (
SELECT
Agentid,
SUM(AmountRecevied) as Amount
FROM collection
GROUP BY AgentID
ORDER BY Amount DESC
LIMIT 4
) AS C, (SELECT #rownum := 0) r
In case of amount matching for different agentids, then, I believe, ranks should be assigned same.
This solution should help you:
select
/*case when rank>6 then '' else rank end as */
rank, agentid, amount
from (
select agentid, #ca:=amount amount
, case when #pa=#ca then #rn:=#rn
else #rn:=( #rn + 1 )
end as rank
, #pa:=#ca as temp_currAmount
from ( select agentid, sum(amount) as amount
from agents
group by agentid
order by amount
) amounts_summary,
(select #pa:=0, #c0:=0,
#rn:=0) row_nums
order by rank desc
) results
where rank > 6
order by rank
;
Demo # MySQL 5.6.6 Fiddle
And if you want no display ranks greater than '6' but empty, then
just uncomment the case line and comment the where condition line
select
case when rank>6 then '' else rank end as
rank, agentid, amount
from (
select agentid, #ca:=amount amount
, case when #pa=#ca then #rn:=#rn
else #rn:=( #rn + 1 )
end as rank
, #pa:=#ca as temp_currAmount
from ( select agentid, sum(amount) as amount
from agents
group by agentid
order by amount
) amounts_summary,
(select #pa:=0, #ca:=0,
#rn:=0) row_nums
order by rank
) results
-- where rank > 6
order by rank
;
You can modify asc or desc as required.
Demo # MySQL 5.6.6 Fiddle

Mysql query to get the row position in a table

I have table with id (store user id) and score in different match. I want what is the position of a user.
So for i try this sql fiddle;
in this I am getting all the row but I need only user having id 3 and it position in the table.
like this:
Score Postion
26 3
Even i try to do like this but no success
MySql: Find row number of specific record
With MySQL, how can I generate a column containing the record index in a table?
I got the answer: http://sqlfiddle.com/#!2/b787a/2
select * from (
select T.*,(#rownum := #rownum + 1) as rownum from (
select sum(score) as S,id from mytable group by id order by S desc ) as T
JOIN (SELECT #rownum := 0) r
) as w where id = 3
Updated sqlfiddle and above query. Now it is working perfectly.
I think this should do the trick:
SELECT totalScore, rownum FROM (
SELECT id,sum(score) AS totalScore,(#rownum := #rownum + 1) AS rownum
FROM mytable
JOIN (SELECT #rownum := 0) r
group by id) result
WHERE result.ID = 3;
just add a where clause
select x.id,x.sum,x.rownum
from(
select id,sum(score) as sum,(#rownum := #rownum + 1) as rownum
from mytable
JOIN (SELECT #rownum := 0) r
group by id
) x
where id =3