I would like to achieve SELECT TOP PERCENT in MySQL.
I used Victor Sorokin's idea in Select TOP X (or bottom) percent for numeric values in MySQL, and got the following query:
SELECT x.log AS Login,
AVG(x.PROFIT) AS 'Expected Shortfall',
MAX(x.PROFIT) AS '40%VaR'
FROM
(SELECT t.PROFIT,
@counter := @counter +1 AS counter,
t.LOGIN AS log
FROM (SELECT @counter:=0) initvar, trades AS t
WHERE t.LOGIN IN (100,101)
ORDER BY t.PROFIT) AS x
WHERE x.counter <= (40/100 * @counter)
GROUP BY x.log
Which return the following result:
Login | Expected Shortfall | 40%VaR |
---|---|---|
101 | -85 | -70 |
This works when I change WHERE t.LOGIN IN (100,101)
to a single value like WHERE t.LOGIN=100
. Whereby it will return me values for each login as following:
Login | Expected Shortfall | 40%VaR |
---|---|---|
100 | -4.5 | -4 |
Login | Expected Shortfall | 40%VaR |
---|---|---|
101 | -95 | -90 |
I'm not really sure what is happening and I was wondering if there is a way to use the query for multiple accounts or there is a better way to solve the issue? Was thinking of a LOOP statement?
I'm currently using MySQL version 5.7.34. Please do not hesitate to let me know if any clarification is needed. Any ideas would be much appreciated!
Edit: To replicate the issue:
CREATE TABLE trades (
TICKET int(11) PRIMARY KEY,
LOGIN int(11),
PROFIT double)
INSERT INTO trades (TICKET,LOGIN,PROFIT)
VALUES
(1,100,-5),
(2,100,-4),
(3,100,-3),
(4,100,-2),
(5,100,-1),
(6,101,-100),
(7,101,-90),
(8,101,-80),
(9,101,-70),
(10,101,-60),
(11,101,-50),
(12,101,500)
The expected output is just like the outputs you would get if you ran the query for 100 and 101 separately:
Expected Output
LOGIN | ES | 40%VAR |
---|---|---|
100 | -4.5 | -4 |
101 | -95 | -90 |