SQL查询分组依据并选择最大绝对值

时间:2018-03-27 16:25:01

标签: sql sql-server group-by max absolute

"表1"结构如下图所示:

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 

我需要从上表“Table1”中选择记录并将它们复制到“Table2”。 我需要从table1中选择满足以下条件的玩家记录: 如果玩家有多个client_names或多个client_country,则选择具有最大评级值的记录。如果它是negavie,则取该值的绝对值。即如果评级为-10和-34,则取最大的绝对值。一世。 e取绝对值为10,34,最大值为34。 例如:Kumar有3个差异客户端名称或3个差异client_country,因此对于kumar,应该在获取其绝对值后选择评级为32的记录。 以下是预期产量:

    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'

3 个答案:

答案 0 :(得分:0)

我猜这个查询会起作用:

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

答案 1 :(得分:0)

如果您的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的行。将随机选择其中一个,但#2将选择所有。

答案 2 :(得分:0)

您可以尝试这样的事情:

cType