I recived some great help earlier today but it was more difficult when I should implement it in my query than I thought. My real query includes several left joins.
I want to add two columns, T3MOutput and T1GOutput that shows a 10-1 ranking based on T3M and T1G columns. The gratest value there should get 10 in the ranking scale and the lowest (negative value) should get 1. Notice ! A horse race can be less than 15 horses at start. After the ten best values recived 10-1 the rest should also get value 1.
Fiddle: http://sqlfiddle.com/#!2/9c5fc/4
Where should I implement this line of code or some other solution? I only get the value 1 throughout..
(SELECT @row:=11 r) rows
Here are all code:
SELECT
base.number as NR,
rank.rpo AS RPO,
rank.rsp AS RSP,
rank.rsv AS RSV,
timer.t3m AS T3M, CASE WHEN @row>1 THEN @row:=@row-1 ELSE 1 END T3MOutput,
timer.t1g AS T1G, CASE WHEN @row>1 THEN @row:=@row-1 ELSE 1 END T1GOutput
FROM round
LEFT JOIN base
ON round.id = base.round_id
LEFT JOIN rank
ON round.id = rank.round_id AND rank.number = base.number
LEFT JOIN timer
ON round.id = timer.round_id AND timer.number = base.number
ORDER BY nr
First
SELECT MIN(timer.t3m) AS MinT3M, MAX(timer.t3m) AS MaxT3M,
MIN(timer.t1g) AS MinT1G, MAX(timer.t1g) AS MaxT1G
FROM round INNER JOIN timer ON round.id = timer.round_id
WHERE round.round_date = '2013-03-22'
AND round.gameform = 'V65'
AND round.gameform_info = 'V65-1'
AND round.gameform not like "OSPEC";
Then you can use the calculation which Richard proposed while I was typing this.
See the SQL Fiddle here which uses your data.
Assuming that you are trying to rank these values, One possible way of doing this is first determine the min and max values of T3M and T1G, then using something like this:
SELECT ...,
((T3M-@T3M_Min)/(@T3M_Max-@T3M_Min))*9+1 as T3MOutput,
((T1G-@T1G_Min)/(@T1G_Max-@T1G_Min))*9+1 as T1GOutput
There may have to be some conversion to an integer value
It is a bit tricky, maybe is it this what you are looking for?
SELECT
q2.*,
CASE WHEN @row>1 AND T1G is not NULL THEN @row:=@row-1 ELSE 1 END T1GOutput
FROM (
SELECT
q1.*,
CASE WHEN @row>1 AND T3M is not NULL THEN @row:=@row-1 ELSE 1 END T3MOutput
FROM (
SELECT
base.number as NR,
rank.rpo as RPO,
rank.rsp as RSP,
rank.rsv as RSV,
timer.t3m as T3M,
timer.t1g AS T1G
FROM
round LEFT JOIN base
ON round.id = base.round_id
LEFT JOIN rank
ON round.id = rank.round_id and rank.number = base.number
LEFT JOIN timer
ON round.id = timer.round_id and timer.number = base.number
order by T3M DESC
) q1, (SELECT @row:=11) rows
) q2, (SELECT @row:=11) rows
ORDER BY
T1G
Please see fiddle here.
来源:https://stackoverflow.com/questions/15623494/convert-decimal-value-to-top-10