在一个表中从最高到最低的SQL顺序,引用UPDATE中的另一个表

时间:2017-02-28 22:20:31

标签: sql sql-server sql-server-2012

嘿所有我需要以下表格,以便从一个匹配另一个的数据中获取数据,并根据TempVersion的int从最高到最低。

UPDATE
    net_Users
SET
    net_Users.DefaultId = b.TId
FROM
    (SELECT 
        TOP 1 IndivId, 
        TId 
     FROM 
        UTeams 
     WHERE 
        UTeams.[Active] = 1 
     ORDER BY 
        TempVersion DESC
    ) AS b
WHERE
    net_Users.IndivId = b.IndivId 

在上面我试图从最高 TempVersion 订购到最低价。

上面的查询似乎只是使用 TempVersion 更新了其中一条记录,然后停在那里。我需要循环查找具有相同 IndivId 匹配的所有关联用户。

任何人都可以帮我解决这个问题吗?

示例数据

net_Users:

name    | DefaultId | IndivId | etc...
--------+-----------+---------+-------
Bob     |           | 87      | etc...
Jan     |           | 231     | etc...
Luke    |           | 8       | etc...

UTeams:

IndivId | TempVersion | etc...
--------+-------------+-------
8       | 44          | etc...
17      | 18          | etc...
8       | 51          | etc...
8       | 2           | etc...
7       | 22          | etc...
8       | 125         | etc...
87      | 10          | etc...
14      | 88          | etc...
8       | 5           | etc...
15      | 54          | etc...
65      | 11          | etc...
87      | 15          | etc...
39      | 104         | etc...

我需要的输出是(将选择IndivId 8):

在net_users中:

Name | DefaultId | IndivId | etc...
-----+-----------+---------+-------
Luke | 125       | 8       | etc...
Luke | 51        | 8       | etc...
Luke | 44        | 8       | etc...
Luke | 5         | 8       | etc...
Luke | 2         | 8       | etc...

1 个答案:

答案 0 :(得分:1)

我认为这就是你想要做的事情:

update net_Users
  set net_Users.DefaultId = coalesce((
    select top 1 TId
    from UTeams
    where UTeams.[Active] = 1
      and net_Users.IndivId = UTeams.IndivId
    order by u.TempVersion desc
    )
    ,net_Users.DefaultId
    )

使用cross apply()

的另一种方式
update n
  set DefaultId = coalesce(x.Tid,n.DefaultId)
from net_Users as n
cross apply (
  select top 1 TId
  from UTeams as u
  where u.[Active] = 1
    and n.IndivId = u.IndivId
  order by u.TempVersion desc
) as x

使用common table expressionrow_number()

执行此操作的另一种方法
with cte as (
  select 
    n.IndivId
  , n.DefaultId
  , u.Tid
  , rn = row_number() over (
      partition by n.IndivId 
      order by TempVersion desc
      )
  from net_users as n
    inner join UTeams as u
      on n.IndivId = u.IndivId
  where u.[Active]=1
)
update cte
set DefaultId = Tid
where rn = 1