T-SQL:如何用用户部门填充列?

时间:2016-11-18 17:39:02

标签: sql sql-server tsql

我意识到这项任务应该非常简单,但出于某种原因我暂时无法理解。搜索类似的问题也无济于事。

所以,假设我有两个表: Documents DepartmentsAndUsers

--- Documents --- (one document could have any user as its author)
DocumentID   AuthorID   DepartemntID
1            User1      null
2            User2      null
3            User3      null
4            User1      null
5            User4      null

--- DepartmentsAndUsers --- (a user could be in any number of departments) 
DepartmentID   UserID
Dept1          User1
Dept1          User2
Dept1          User3
Dept2          User4
Dept2          User5
Dept3          User1
Dept3          User3

如何在 DepartmentsAndUsers 表中的第一个(或任何)用户部门填写 Documents 表中的 DepartemntID 列?

例如,User1在Dept1和Dept3中,因此 Documents Documents 1和4应该用Dept1或Dept3值填充。

请不要在标准化点上考虑这一点,因为我无法更改表格的任何逻辑。

任何有关同一场景的解决方案的帮助或链接都将受到高度赞赏。

2 个答案:

答案 0 :(得分:3)

with cte as( 
    select 
        UserID,
        max(DepartmentID) as DepartmentID
    from DepartmentsAndUsers
    group by UserID)

select 
    d.DocumentID,
    d.AuthorID,
    cte.DepartmentID
from Documents d
inner join cte on cte.UserID = d.AuthorID

答案 1 :(得分:1)

这也应该有效:

UPDATE Documents SET DepartemntID = E.DepartemntID
FROM Documents D
LEFT JOIN (
    SELECT UserID, MIN(DepartemntID) DepartemntID
    FROM DepartmentsAndUsers
    GROUP BY UserID
) E ON E.UserID = D.AuthorID

以下是一个例子:

DECLARE @Documents TABLE (
    DocumentID INT,
    AuthorID VARCHAR(16),
    DepartemntID VARCHAR(16)
)

DECLARE @DepartmentsAndUsers TABLE (
    DepartemntID VARCHAR(16),
    UserID VARCHAR(16)
)

INSERT @Documents VALUES
(1, 'User1', NULL),
(2, 'User2', NULL),
(3, 'User3', NULL),
(4, 'User1', NULL),
(5, 'User4', NULL)

INSERT @DepartmentsAndUsers VALUES
('Dept1', 'User1'),
('Dept1', 'User2'),
('Dept1', 'User3'),
('Dept2', 'User4'),
('Dept2', 'User5'),
('Dept3', 'User1'),
('Dept3', 'User3')

UPDATE @Documents SET DepartemntID = E.DepartemntID
FROM @Documents D
LEFT JOIN (
    SELECT UserID, MIN(DepartemntID) DepartemntID
    FROM @DepartmentsAndUsers
    GROUP BY UserID
) E ON E.UserID = D.AuthorID

SELECT * FROM @Documents