SQL查询group by和select最大绝对值

SQL query group by and select the maximum absolute value

"Table1"结构如下图:

source table table1

Player_NAME ||  Player_NUMBER  ||   Client_name ||  Client_country  || Player_country||    Rating   

GERALD  || A1234    || BENFIELD || IND ||   IND ||  76            
GERALD   ||A6578    || ROTFIELD ||  USA || USA ||   64   
KUMAR   || P1234    || LFV  || ARG  || ARG ||   -24  
KUMAR   || P5678    ||JEURASIN ||   ARG ||  TUR ||-32  
KUMAR   || P0101    ||ARGENIA   ||ARG   ||POL   ||-16  
ANDREW  ||R1234 ||  GENMAD  || GER  || GER ||   23 

我需要select把上面table“表1”的记录复制到“表2”。 我需要 select 来自 table1 的播放器记录,它满足以下条件: 如果玩家有多个client_names或多个client_country,则select具有最大值的记录。如果它是负值,则取该值的绝对值。即,如果评级为 -10 和 -34,则取最大的绝对值。一世。 e 通过取绝对值,它是 10,34,34 是最大的。 例如:Kumar 有 3 个 diff 客户端名称或 3 个 diff client_country,因此对于 kumar,评级为 32 的记录在取其绝对值后应该是 selected。 以下是预期的输出:

    Player_NAME ||  Player_NUMBER   ||Client_name ||    Client_country  ||Player_country||  Rating    

GERALD  || A1234    || BENFIELD||   IND||   IND||   76    
KUMAR   || P5678    || JEURASIN ||ARG   ||TUR ||    -32     
ANDREW  || R1234    || GENMAD   ||GER   ||GER   || 23 

destination table-'table2'

我想,这个查询会起作用:

select
max(abs(Rating))
from  Table1
group by Player_NAME

要向Table2中插入数据,可以这样操作:

INSERT INTO Table2 (
    Player_Name,
    Player_Number,
    Cliet_Name,
    Client_country,
    Player_country,
    Rating
)
SELECT
    t1.Player_Name,
    t1.Player_Number,
    t1.Cliet_Name,
    t1.Client_country,
    t1.Player_country,
    t1.Rating
FROM Table1 t1
INNER JOIN (
    SELECT
        Player_NAME,
        MAX(ABS(Rating)) as Rating
    FROM  Table1
    GROUP BY Player_NAME
) t2 ON t2.Player_NAME = t1.Player_NAME AND ABS(t1.Rating) = t2.Rating

如果您的 DBMS 支持分析函数,您可以使用ROW_NUMBER:

select ...  -- all columns but rn
from
 (
   select ...  -- all columns
      ,row_number() 
       over (partition by player_name
             order by abs(Rating) desc as rn
   from table1
 ) as dt
where rn = 1;

否则使用相关子查询:

select *
from table1 as t1
where abs(rating) = 
 ( select max(abs(rating))
   from table1 as t2
   where t1.player_name = t2.player_name
 ) 

如果您有多个行具有相同的 max(abs(rating)) #1。将 select 随机选择其中之一,但 #2 将 select 所有。

您可以尝试这样的操作:

INSERT INTO Table2
    (
        Player_Name,
        Player_Number,
        Cliet_Name,
        Client_country,
        Player_country,
        Rating
    )
            SELECT
                Player_Name,
                Player_Number,
                Cliet_Name,
                Client_country,
                Player_country,
                MAX(ABS(Rating)) OVER (PARTITION BY player_Name ORDER BY Cliet_Name,
            Client_country) as Rating
            FROM
                table1