将一个表的前N个结果的特定列映射到另一个表的列

时间:2014-07-11 12:07:58

标签: sql tsql sql-server-2012

我有一个像这样定义的用户表:

CREATE TABLE users
(
    [id] int IDENTITY NOT NULL PRIMARY KEY,
    [populartag1id] int NULL,
    [populartag2id] int NULL,
    [populartag3id] int NULL,

    constraint fk_populartag1id_users foreign key(populartag1id) references tags(id),
    constraint fk_populartag2id_users foreign key(populartag2id) references tags(id),
    constraint fk_populartag3id_users foreign key(populartag3id) references tags(id),
);

和查询

SELECT * FROM v_user_tag_counts ORDER BY userid, count DESC
返回的

返回如下行:

userid  tagid   count
7       1       2
7       161     1
7       26      1
7       2       1
8       150     1
8       98      1
8       89      1
8       20      1
8       157     1
8       19      1
8       289     1
8       116     1

现在我想将查询返回的第一个,第二个和第三个tagid映射到一个更新(夜间作业)中所有用户的populartag1id,populartag2id和populartag3id列。

我注意到PIVOT在这里是否正确。建议?

1 个答案:

答案 0 :(得分:2)

我会通过手动支点来做到这一点:

select ut.userid,
       max(case when seqnum = 1 then ut.tagid end) as populartag1id,
       max(case when seqnum = 2 then ut.tagid end) as populartag2id,
       max(case when seqnum = 3 then ut.tagid end) as populartag3id
from (select *, row_number() over (partition by userid order by count desc) as seqnum
      from v_user_tag_counts
     ) ut
group by ut.userid;

此格式适合插入第一个表格。