删除除两列的最新唯一组合之外的所有组合

时间:2013-11-11 15:33:59

标签: sql tsql sql-server-2012

我有一个表变量,我需要从中删除行。此查询显示表的内容:

SELECT
    useractionId,
    userId,
    actionId,
    ROW_NUMBER() OVER (PARTITION BY userid, actionId ORDER BY dateOfApplication ASC) AS applicationOrder, -- put into order of application (earliest first)
    dateOfApplication
FROM
    @tbl_appliedhistory;

结果如下,并提供每次用户完成操作的记录:

编辑 - 在只有一个用户ID / actionid组合的末尾添加了额外的行

useractionId userId     actionId    applicationOrder     dateOfApplication
----------- ----------- ----------- -------------------- -----------------------
7665        3           2479        1                    2013-09-08 18:17:23.953
7675        3           2479        2                    2013-09-08 18:18:56.063
7685        3           2479        3                    2013-09-08 18:21:21.487
8286        3           2695        1                    2013-11-07 09:28:03.817
8287        3           2695        2                    2013-11-11 13:47:11.337
8289        3           2695        3                    2013-11-11 13:47:56.390
8291        3           2695        4                    2013-11-11 13:48:11.957
8284        87453       2695        1                    2013-11-06 15:08:40.823
8285        87453       2695        2                    2013-11-06 15:09:26.167
8288        87453       2695        3                    2013-11-11 13:47:11.337
8290        87453       2695        4                    2013-11-11 13:47:56.390
8291        89000       3000        1                    2013-11-12 15:50:50.000

对于userId / actionId列值的每个组合,我需要删除除applicationOrder的最高值之​​外的所有值(该特定actionId的最新已完成操作) 。因此,一旦删除,剩下的行将是:

useractionId  userId    actionId    applicationOrder     dateOfApplication
----------- ----------- ----------- -------------------- -----------------------
7685        3           2479        3                    2013-09-08 18:21:21.487
8291        3           2695        4                    2013-11-11 13:48:11.957
8290        87453       2695        4                    2013-11-11 13:47:56.390
8291        89000       3000        1                    2013-11-12 15:50:50.000

这些结果显示用户完成每个操作的最新日期。我很感激您在识别这些行时提供任何帮助。

2 个答案:

答案 0 :(得分:2)

您不能只按dateOfApplication desc 排序,然后使用row_number>删除所有内容。 1?

像这样:

;WITH CTE AS 
(
     SELECT
         useractionId,
         userId,
         actionId,
         ROW_NUMBER() OVER (PARTITION BY userid, actionId ORDER BY dateOfApplication DESC) AS applicationOrder, -- put into order of application (earliest first)
         dateOfApplication
     FROM @tbl_appliedhistory
)

DELETE FROM CTE WHERE applicationOrder > 1

答案 1 :(得分:2)

在以下示例中,而不是ORDER BY dateOfApplication ASC使用ORDER BY dateOfApplication DESC。

;WITH cte AS
 (SELECT ROW_NUMBER() OVER (PARTITION BY userid, actionId ORDER BY dateOfApplication DESC) AS applicationOrder
  FROM Table1
  )
DELETE cte
WHERE applicationOrder != 1

SQLFIddle上的演示