我有一个查询,我加入了employee表和logs表来显示每个员工的日志。问题是我需要删除那些重复的列值(仅将emp详细信息显示给每个员工的第一行)。有谁知道如何在Excel或SQL Server中执行此操作?
SELECT e.Employee, e.Position, e.Dept, l.Actioner, s.Status, l.ActionDate
FROM employee e
LEFT JOIN logs l ON e.EmpNo = l.EmpNo
INNER JOIN Status s ON l.StatusId = s.Id
ORDER BY l.Employee, l.ActionDate
原始输出
Employee |Position |Dept |Actioner |Action |ActionDate
emp1 |Manager |IT |emp1 |Submit |01/01/2017
emp1 |Manager |IT |emp2 |Verify |01/02/2017
emp1 |Manager |IT |emp3 |Approve |01/03/2017
emp2 |Supervisor |HR |emp2 |Submit |01/12/2017
emp2 |Supervisor |HR |emp3 |Verify |01/13/2017
emp2 |Supervisor |HR |emp4 |Approve |01/14/2017
期望输出
Employee |Position |Dept |Actioner |Action |ActionDate
emp1 |Manager |IT |emp1 |Submit |01/01/2017
|emp2 |Verify |01/02/2017
|emp3 |Approve |01/03/2017
emp2 |Supervisor |HR |emp2 |Submit |01/12/2017
|emp3 |Verify |01/13/2017
|emp4 |Approve |01/14/2017
注意:如果可以使用Excel功能解决此问题,我更喜欢。谢谢!
答案 0 :(得分:1)
以下是2012年之前在SQL Server中执行此操作的一种方法(引入LAG
函数时)。
使用包含ROW_NUMBER
的公用表格式和CASE
表达式仅返回第一个Employee
,Position
和Dept
:
;WITH CTE AS
(
SELECT e.Employee,
e.Position,
e.Dept,
l.Actioner,
s.Status,
l.ActionDate,
ROW_NUMBER() OVER(PARTITION BY e.Employee ORDER BY l.Employee, l.ActionDate) As rn
FROM employee e
LEFT JOIN logs l ON e.EmpNo = l.EmpNo
INNER JOIN Status s ON l.StatusId = s.Id
)
SELECT CASE WHEN rn = 1 THEN e.Employee END As Employee,
CASE WHEN rn = 1 THEN e.Position END As Position,
CASE WHEN rn = 1 THEN e.Dept END As Dept,
l.Actioner,
s.Status,
l.ActionDate
FROM CTE
ORDER BY l.Employee, l.ActionDate