小编典典

自行加入以获取员工经理姓名

sql

您好,我有一个员工表,其中包含以下列

Emp_id, Emp_Name and Mgr_id.

我正在尝试创建一个将列出的视图

Emp_id, Emp_name, Mgr_id and Mgr_name(通过交叉连接Employee表)。我尝试了外部联接,内部联接等,但无法正确完成。

任何帮助都将受到高度赞赏。

CREATE TABLE [dbo].[tblEmployeeDetails](
[emp_id] [bigint] NOT NULL, 
[emp_name] [nvarchar](200) NULL,    
[emp_mgr_id] [bigint] NULL, CONSTRAINT [PK_tblEmployeeDetails] PRIMARY KEY CLUSTERED (
[emp_id] ASC )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY] ) ON [PRIMARY]

阅读 175

收藏
2021-03-10

共1个答案

小编典典

CREATE VIEW AS
SELECT e1.emp_Id EmployeeId, e1.emp_name EmployeeName, 
       e1.emp_mgr_id ManagerId, e2.emp_name AS ManagerName
FROM   tblEmployeeDetails e1
       JOIN tblEmployeeDetails e2
       ON e1.emp_mgr_id = e2.emp_id

编辑 :如果emp_mgr_id为null,则左联接将起作用。

CREATE VIEW AS 
SELECT e1.emp_Id EmployeeId, e1.emp_name EmployeeName,  
       e1.emp_mgr_id ManagerId, e2.emp_name AS ManagerName 
FROM   tblEmployeeDetails e1 
       LEFT JOIN tblEmployeeDetails e2 
       ON e1.emp_mgr_id = e2.emp_id
2021-03-10