使用Excel(或SQL)合并或删除列中的重复值

时间:2017-08-16 06:02:59

标签: sql sql-server excel

我有一个查询,我加入了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功能解决此问题,我更喜欢。谢谢!

1 个答案:

答案 0 :(得分:1)

以下是2012年之前在SQL Server中执行此操作的一种方法(引入LAG函数时)。

使用包含ROW_NUMBER的公用表格式和CASE表达式仅返回第一个EmployeePositionDept

;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