要在manager_id上打印Max sal

时间:2015-11-27 10:24:09

标签: sql sql-server

我有这张桌子:

id  mgr_id  sal
1   5       5000
2   5       6000
3   6       7000
4   6       8000

我期待这个输出:

id  mgr_id  sal MaX_sal
1   5      5000 6000
2   5      6000 6000
3   6      7000 8000
4   6      8000 8000

基于mgr_id选择max sal并在id。前面打印。

提前致谢。

5 个答案:

答案 0 :(得分:0)

可能是select中的子选择(虽然所有子选择都有点慢):

select id, mgr_id, sal, (select max(sal) from mytable n2 
where n2.mgr_id = mytable.mgr_id) as max_sal from mytable 

答案 1 :(得分:0)

使用 SQL Server 2012 ,只需使用此查询:

SELECT d.id, d.mgr_id, d.sal, MAX(sal) over(partition by mgr_id)
FROM @data d

您可以将此查询与 SQL Server< 2012:

一起使用
SELECT d.id, d.mgr_id, d.sal, m.mx
FROM @data d
INNER JOIN (
    SELECT mgr_id, mx = MAX(sal) FROM @data
    GROUP BY mgr_id
) m
ON m.mgr_id = d.mgr_id;

SQL Server> = 2005的另一个选项:

SELECT d.id, d.mgr_id, d.sal, m.mx
FROM @data d
CROSS APPLY (SELECT mx = MAX(sal) FROM @data m WHERE m.mgr_id = d.mgr_id) m(mx)

示例数据:

Declare @data table([id] int, [mgr_id] int, [sal] int);

INSERT INTO @data([id], [mgr_id], [sal])
VALUES
    (1, 5, 5000),
    (2, 5, 6000),
    (3, 6, 7000),
    (4, 6, 8000)
;

答案 2 :(得分:0)

这甚至可以在SQL Server 6.5中使用

SELECT id, mgr_id, sal, 
    (
        SELECT MAX(sal) 
        FROM employees mgr 
        WHERE mgr.mgr_id = emp.mgr_id
    ) AS max_sal
FROM
   employees emp

这适用于SQL Server 2005:

WITH max_sals AS
(

    SELECT mgr_id, MAX(sal) AS max_sal
    FROM employees
    GROUP BY mgr_id
)
SELECT emp.*, max_sals.max_sal
FROM
    employees emp
    LEFT JOIN max_sals
        ON emp.mgr_id = max_sals.mgr_id

这是使用partiton:

SELECT emp.*, MAX(emp.sal) OVER (PARTITION BY emp.mgr_id) AS max_sal
FROM employees emp

示例数据和表格:

CREATE TABLE employees
(
  id int,
  mgr_id int,
  sal int

)

INSERT INTO employees VALUES
(1,5,5000),
(2,5,6000),
(3,6,7000),
(4,6,8000)

答案 3 :(得分:0)

通过mrg_id创建一个子表分组,以获得每个mrg_id的最大Sal,然后将其与mrg_id上的主表连接起来 - 试试这个:

declare @table table (id int,mrg_id int,sal decimal(10,0))

insert into @table
select 1,   5,       5000 union all
select 2,   5,       6000 union all
select 3,   6,       7000 union all
select 4,   6,       8000 

/***** change @table with your table name *****/ 
SELECT 
t.id,
t.mrg_id,
t.sal,
t1.max_sal
FROM @table t
LEFT JOIN 
(SELECT 
mrg_id,
MAX(sal) max_sal
FROM @table
group by 
mrg_id) t1
on t.mrg_id=t1.mrg_id

答案 4 :(得分:-1)

尝试交叉申请,

seq