Как найти наибольшее значение в столбце и отобразить его с флагом «Величайшее значение» и отобразить оставшуюся часть нового значения столбца как «Не самое большое» - PullRequest
0 голосов
/ 29 апреля 2020

У меня есть таблица UnitCheck:

enter image description here

enter code here

Я хочу добавить новый столбец, который вернет мне значение Greatest, если значение CostToRestaff является наибольшим и должно возвращаемое значение Not Greatest для всех остальных значений кода входа здесь CostToRestaff.

CostToRestaff - это вычисляемый столбец с формулой: 0 * FullDuty C + 10 * Wounded C + 25 * KilledC;

enter code here

отредактировано:

Я пытался больше на этих линиях. Любая идея, где я иду не так?

''''''

if Unit_ID = A then --A is the user parameter for my procedure
Set check1 = 0 * FullDutyC + 10 * WoundedC + 25 * KilledC;
end if;

if Unit_ID = B then --B is the user parameter for my procedure
Set check2 = 0 * FullDutyC + 10 * WoundedC + 25 * KilledC;
end if;

if Unit_ID = C then --C is the user parameter for my procedure
Set check3 = 0 * FullDutyC + 10 * WoundedC + 25 * KilledC;
end if;
if check1 > check2 AND check1 > check3 then
set Rejection = /*  this is where i need the final answer which should be 
the value itself for eg: 125 - since it is the highest value*/ where Unit_ID = 
A;
elseif check2 > check3 AND check2 > check1 then
Set Rejection = /* this is where i need the final answer in this case since it is not the highest value then it should jump to the else condition*/ where 
Unit_ID = B;
elseif check3 > check1 AND check3 > check2 then
Set Rejection = /* this is where i need the final answer in this case since it is not the highest value then it should jump to the else condition*/ where Unit_ID = 
C;
else set Rejection = "Not Greatest"
end if;

''''''

1 Ответ

0 голосов
/ 29 апреля 2020

Предполагая MySQL 8.0, вы можете использовать оконные функции:

select
    t.*,
    (rank() over(order by CostToRestaff desc) = 1) isGreatest
from mytable t

Это дает вам флаг 0/1, который указывает, имеет ли ток наибольшее значение CostToRestaff во всей таблице - что я считаю более значимым, что строка '(Not) Greatest'. Если есть верхние связи, они все получат флаг 1.

Если вы хотите использовать это в качестве строкового значения:

select
    t.*,
    case when rank() over(order by CostToRestaff desc) = 1
        then 'Greatest'
        else 'Not Greatest'
    end isGreatest
from mytable t

В более ранних версиях вы можете использовать подзапрос или объединение для вычисления максимального значения:

select
    t.*,
    (select max(CostToRestaff) from mytable) =  CostToRestaff isGreatest
from mytable t
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...