分组+案例陈述

时间:2017-03-14 09:03:13

标签: sql group-by case

我想用casegroup by声明更新我的表格。

我的玩家表格包含salary列,每行都有group_name

我想更新所有薪水超过平均团薪的球员。

首先,我试图列出名称,球员薪水和球队平均薪水。我有这个问题,我很乐意得到帮助。

select  first_name,
        last_name,
        group_name,
        salary,
        (
          select round(avg(salary),2) as salary
          from players
          group by group_name
        )
from players

感谢您的帮助!!!

4 个答案:

答案 0 :(得分:1)

我仍然不知道您正在使用哪个DBMS。所以我只能猜测。以下是更新命令 SQL服务器:

update p set salary=avgsal+100 -- enter your formula here
from players p inner join
   (  select group_name gname,round(avg(salary),2) as avgsal
      from players
      group by group_name
    ) grped on gname=group_name
where salary>avgsal;

和MySql:

update players inner join
   (  select group_name gname,round(avg(salary),2) as avgsal
      from players
      group by group_name
    ) grped on gname=group_name
set salary=avgsal+100 -- enter your formula here!
where salary>avgsal;

在上述命令中,我将相关玩家的当前薪水替换为该组的平均薪水+100。这当然是您应该输入自己的公式的地方!

答案 1 :(得分:0)

在JOIN语句中使用GROUP BY子句:

SELECT  first_name,last_name,group_name,salary
FROM players
JOIN 
(
  SELECT ROUND(AVG(salary),2) as salary , group_name
  FROM PLAYERS
  GROUP BY group_name
) A ON A.group_name = players.group_name

答案 2 :(得分:0)

这个sql会找到相应的玩家并用该组的平均工资更新他的工资: -

MERGE INTO MyTable MyTable
USING
(
    SELECT a.player,
           a.[group],
           a.sal,
           b.sal2
    FROM MyTable a
         INNER JOIN
    (
        SELECT [group],
               AVG(Sal) sal2
        FROM MyTable
        GROUP BY [group]
    ) b ON a.[group] = b.[group]
           AND a.sal > b.sal2
) YY
ON YY.player = MyTable.player
   AND YY.[group] = MyTable.[group]
    WHEN MATCHED
    THEN UPDATE SET
                    MyTable.sal = yy.sal2;

答案 3 :(得分:0)

试试这个@Amit Ben Zur

SELECT Ord.first_name, Ord.last_name,Ord.group_name,
(SELECT round(avg(salary),2)
 FROM Players AS OrdDet
 WHERE Ord.group_name = OrdDet.group_name) AS MaxUnitPrice
FROM Players AS Ord