2

我一直在抨击这个问题已经有一段时间了,而且进展不快;数据必须保持在行级别。

我想保留最早到达的数据,重复有效。Load1 代表一个批次ID。并非所有值都有重复项

我想退货

Code1   Code2   Code3   Load1   LoadTime
a1      a1      a1      1       2013-09-10
a1      a1      a1      1       2013-09-10
a1      a1      a1      1       2013-09-10
a2      a1      a1      2       2013-09-12
a1      a2      a1      3       2013-09-13
a1      a2      a1      3       2013-09-13

有什么建议么?

 CREATE TABLE #Test (
 Code1  varchar(10),
 Code2  varchar(10),
 Code3  varchar(10),
 Load1  varchar(10),
 LoadTime DATE
 )


  INSERT INTO #Test
  VALUES ('a1','a1','a1','1','2013-09-10') --Keep

  INSERT INTO #Test
  VALUES ('a1','a1','a1','1','2013-09-10') --Keep

  INSERT INTO #Test
  VALUES ('a1','a1','a1','1','2013-09-10') --Keep

  INSERT INTO #Test
  VALUES ('a1','a1','a1','2','2013-09-11') --Delete

  INSERT INTO #Test
  VALUES ('a2','a1','a1','2','2013-09-12') --Keep

  INSERT INTO #Test
  VALUES ('a2','a1','a1','3','2013-09-13') --Delete

  INSERT INTO #Test
  VALUES ('a1','a2','a1','3','2013-09-13') --Keep

  INSERT INTO #Test
  VALUES ('a1','a2','a1','3','2013-09-13') --Keep

  INSERT INTO #Test
  VALUES ('a1','a2','a1','4','2013-09-13')-- Delete

  INSERT INTO #Test
  VALUES ('a1','a2','a1','4','2013-09-13')-- Delete
4

2 回答 2

0

您可能想查看row_number()dense_rank()

很难说出从样本数据中删除或保留的逻辑,但类似

;with cte as (
      select *, 
      dense_rank() over (partition by code1,code2,code3 order by loadtime) rn 
      from #test)
    delete #Test
    from #Test t
        inner join cte
            on t.Code1 = cte.Code1
            and t.Code2 = cte.Code2
            and t.Code3 = cte.Code3
            and t.Load1 = cte.Load1
            and t.LoadTime = cte.LoadTime
        where rn>1

(如果您的数据具有唯一 ID,则连接会容易得多)

于 2013-09-24T11:15:51.630 回答
0

您可以使用 SQL Server公用表表达式或 CTE

with cte as (
    select
        dense_rank() over(partition by Code1, Code2, Code3 order by LoadTime, Load1 asc) as rn
    from Table1
)
delete from cte where rn > 1

sql fiddle demo

实际上这个查询在 SQL Server 中非常简单,因为 SQL Server 将简单的公共表表达式视为可更新视图 - 您不必在原始表上加入 cte,您可以delete from cte

于 2013-09-24T11:19:49.100 回答