我正在尝试编写一个查询,如果在更改值之前删除了“重复”值。例如,我有以下数据:
id, date_recived, name1, percent
1, 8/19/13, Joe, 2
2, 8/15/13, Joe, 3
3, 8/12/13, Joe, 2
4, 4/08/13, Joe, 2
在此示例中,我只需删除ID为3的行,因为百分比没有变化。我尝试过使用Row_Number,但是当我按名称进行分区时,数据显示如下:
id, date_recived, name1, percent, Row_Number
1, 8/19/13, Joe, 2, 3
2, 8/15/13, Joe, 3, 1
3, 8/12/13, Joe, 2, 2
4, 4/08/13, Joe, 2, 1
这不起作用,因为1会被抛出,我需要保留它。任何帮助将不胜感激。
谢谢,
编辑:
查询是(来自评论):
WITH feedback_On_Same_Date AS (
SELECT id, received_dt, participant_nm, pretax_deferral_prcnt,
ROW_NUMBER() OVER(PARTITION BY participant_nm, received_dt ORDER BY received_dt DESC, id DESC) AS RowNumberByDt
FROM be_ing_feedback
)
SELECT *, ROW_NUMBER() OVER(PARTITION BY participant_nm, pretax_deferral_prcnt ORDER BY received_dt ASC, id ASC) AS RowNumberByDef
FROM feedback_On_Same_Date
WHERE RowNumberByDt = 1
ORDER BY participant_nm ASC, received_dt DESC
答案 0 :(得分:1)
听起来你想要删除“前一个”相同的行。
为此,我将使用Row_Number()函数和自连接:
; WITH cte AS (
SELECT id
, date_recived
, name1
, percent
, Row_Number() OVER (PARTITION BY name ORDER BY date_recived) As seq
FROM your_table
)
SELECT *
FROM cte As curr
LEFT
JOIN cte As prev
ON prev.name1 = curr.name1
AND prev.seq + 1 = curr.seq
查看此查询返回的数据,然后只需添加WHERE
子句即可获取要删除的记录。
我会将其余部分留给您;-)
答案 1 :(得分:0)
如果您使用的是SQL Server 2012,请使用lag()
功能:
select id, date_recived, name1, percent
from (select t.*,
lag(percent) over (partition by name1 order by date_received) as prev_percent
from t
) t
where percent <> prev_percent or prev_percent is null;