消除SQL中的重复记录

时间:2016-07-08 10:22:11

标签: sql sql-server

我有一个名为<TextView android:id="@+id/btn1" android:layout_width="match_parent" android:layout_height="48dp" android:background="#399" android:layout_marginBottom="4dp" android:clipChildren="false" android:clipToPadding="false" android:gravity="center" android:text="Text1" /> <TextView android:id="@+id/btn2" android:layout_width="match_parent" android:layout_height="48dp" android:layout_below="@+id/btn1" android:background="#399" android:clipChildren="false" android:layout_marginBottom="4dp" android:clipToPadding="false" android:gravity="center" android:text="Text2Text2Text2Text2" /> <android.support.design.widget.CoordinatorLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/btn2" android:clipChildren="false" android:clipToPadding="false"> <TextView android:id="@+id/content_to_overlap" android:layout_width="match_parent" android:layout_height="64dp" android:background="#B44" android:gravity="center" android:text="Text3" /> <FrameLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginLeft="24dp" android:clipChildren="false" android:clipToPadding="false" app:behavior_peekHeight="48dp" app:layout_behavior="android.support.design.widget.BottomSheetBehavior" android:background="#8FF0" > <android.support.design.widget.FloatingActionButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="-48dp" /> </FrameLayout> </android.support.design.widget.CoordinatorLayout> 的表,其中包含以下列

attribute_value

attribute_id | start_date | value | latest_ind | mod_dtime 列的值可以是1或0.

我基本上想在这个表上运行一个更新脚本,它找到所有具有公共latest_indstart date等于1的属性,并将最新的ind设置为零除外,在这种情况下记录是最新记录。

我设法将以下SELECT查询放在一起,但我不知道如何将其转换为更新。任何指针都将不胜感激

latest_ind

2 个答案:

答案 0 :(得分:1)

使用UPDATE的{​​{1}}可以派上用场:

CTE

更新操作传播到真实表。因此,如果;WITH ToUpdate AS ( SELECT latest_ind, ROW_NUMBER() OVER (PARTITION BY attribute_id, start_date ORDER BY mod_dtime DESC) AS rn FROM attribute_value WHERE latest_ind = 1 ) UPDATE ToUpdate SET latest_ind = 0 WHERE rn > 1 分区的总体大于1,则更新所有记录但最新的记录。

答案 1 :(得分:1)

可能是这样的

方法1:使用CTE

;WITH T AS
(   SELECT attribute_id, start_date, latest_ind,
    ROW_NUMBER() OVER (PARTITION BY av.attribute_id, av.start_date ORDER BY mod_dtime DESC) RN
    FROM t_attribute_value
    where latest_ind = 1
)
UPDATE T
SET latest_ind = 0
WHERE RN > 1

方法2:您不需要为此

进行CTE
UPDATE T
SET T.latest_ind = 0
FROM t_attribute_value T
INNER JOIN
(
        SELECT attribute_id, start_date, latest_ind,
        ROW_NUMBER() OVER (PARTITION BY av.attribute_id, av.start_date ORDER BY mod_dtime DESC) RN
        FROM t_attribute_value
        where latest_ind = 1
) V
   ON T.attribute_id= V.attribute_id AND V.RN > 1