首页 > 解决方案 > U-SQL 是否接受使用多个 FIRST_VALUE 来删除特定列中的重复项?

问题描述

我有一个表,其中多行重复,因为它们的值不同的两个日期列。

我想知道是否可以接受在这样的两列中使用 FIRST_VALUE 来删除指定列上的重复项:

SELECT
 EmployeeName,
 FIRST_VALUE(StartDateTime) OVER(ORDER BY UpdatedDateTime DESC) AS StartDateTime,
 FIRST_VALUE(UpdatedDateTime) OVER(ORDER BY UpdatedDateTime DESC) AS UpdatedDateTime 
 FROM @Employees;

标签: sqlu-sql

解决方案


如果您需要删除某些字段的重复项,则需要使用ROW_NUMBER()和 CTE:

-- Sample data: dates duplicates
declare @t table (id int, dt date);
insert into @t values
(1, '2018-01-14'),
(1, '2018-01-14'),
(1, '2018-01-15'),
(1, '2018-01-15');
with cte as (
    select *,
           -- assign row number for each partition consisting of same date
           row_number() over (partition by dt order by dt) as cnt
    from @t
)
-- we're interested only in one row (i.e. first)
select id, dt from cte where cnt = 1;

/*
 Output:
+-------+---------+
| id | dt         |
+----+------------+
|  1 | 2018-01-14 |
|----|------------|
|  1 | 2018-01-15 |
+----+------------+
*/

推荐阅读