删除子查询

时间:2017-07-11 10:42:28

标签: sql-server

我有2个表tab1tab2

TAB1

 id    name     monthid  salary   inflow
-----------------------------------------
 1     mohan      1       2000     1000
 1     mohan      3       3000     1000
 1     mohan      4       4500     1600
 1     mohan      2       2500     1200
tab2中的

我想要这个输出:

id  name   salary  inflow 
--------------------------
1   mohan   12000   1600

tab2中,工资栏是tab1的工资总和,流入是最高月份的流入。

我尝试了这个查询:

Insert into tab2(id, name, salary)
    select id, name, sum(salary) 
    from tab1

 update tab2 
 set inflow = (select inflow 
               from tab1 
               where monthid = max(monthid))

但我知道这不是正确的方法。

有人可以帮我纠正这个问题吗?我还想删除子查询。

2 个答案:

答案 0 :(得分:1)

您可以使用row_number,如下所示

Insert into tab2(id, [name], [salary], inflow) 
   Select id, [name], Salary, inflow from (
      Select id, [name], sum(salary) over(partition by id) as Salary,
           inflow, RowN = Row_number() over (partition by id order by monthid desc) from tab1 ) a
   Where a.RowN = 1

如果没有子查询,您可以使用top(1),如下所示

Insert into tab2(id, [name], [salary], inflow)
Select top (1) with ties id, [name], sum(salary) over(partition by id) as salary, inflow
    from tab1 
    order by  Row_number() over (partition by id order by monthid desc)

答案 1 :(得分:1)

DECLARE @tab1 table(id int,name varchar(100),monthid int, salary int,inflow int)

INSERT INTO @tab1

SELECT 1,'Mohan',1,2000,1000

UNION ALL

SELECT 1,'Mohan',3,3000,1000

UNION ALL

SELECT 1,'Mohan',4,4500,1600

UNION ALL

SELECT 1,'Mohan',2,2500,1200




SELECT top 1 
id, name,SUM(salary) OVER(PARTITION BY id) as salary,MAX(inflow) OVER(PARTITION BY id) as inflow
FROM @tab1

OR

SELECT DISTINCT 
id, name,SUM(salary) OVER(PARTITION BY id) as salary,MAX(inflow) OVER(PARTITION BY id) as inflow
FROM @tab1