如何使用游标删除重复的条目

时间:2015-04-03 21:15:08

标签: mysql sql oracle11g oracle-sqldeveloper plsqldeveloper

附图有两张表1和表2

表1:

+-------------------------------------------------+--+
| First_name  Last_name Date_of_birth Customer_ID |  |
+-------------------------------------------------+--+
| ---------   ---------   ---------     -------   |  |
| Anmol        Sharma    12/SEP/1988     A101     |  |
| Anmol        Sharma    12/SEP/1988     A102     |  |
| Pushkar      Gupta     03/feb/1987     A103     |  |
| Pushkar      Gupta     03/Feb/1987     A104     |  |
+-------------------------------------------------+--+

表2:

First_name  Last_name  Date_of_birth   Customer_ID   Updated_timestamp
---------       --------- -------------- ------------ ---------------
Anmol            Sharma      12/SEP/1988      A101        23/Feb/2015
Anmol            Sharma      12/SEP/1988      A102        24/FEb/2015
Anmol            Sharma      12/SEP/1988      A101        25/Feb/2015
Pushkar          Sharma      03/FEB/1987      A104        12/Jan/2015

期望输出:

First_name   Last_name Date_of_birth    Customer_ID 
---------   --------- --------------    ------------
Anmol       Sharma        12/SEP/1988      A101
Pushar      Sharma        03/FEB/1987      A104

问题:

我必须在table1中保留最近更新的Customer_ID(使用table2更新的时间戳列),并使用游标删除表1中的所有其他条目。 表图像

有人可以用光标解释逻辑。

3 个答案:

答案 0 :(得分:1)

使用纯SQL,它将是:

delete from table1
 where customer_id in (
         select customer_id
           from (select customer_id, 
                        row_number() over 
                          (partition by last_name, first_name 
                           order by updated_timestamp desc) rn
                   from table2) t
          where rn > 1)

删除之前分别执行每个子查询以确保它是正确的。在第一个子查询row_number()函数中,返回1表示最近更新的行,2表示第二个,等等。第二个子查询选择除最近的(ID)之外的所有rn > 1,并且它是ID删除。

答案 1 :(得分:0)

DELETE FROM table1 WHERE Customer_ID NOT IN 
(SELECT Customer_ID from table2 
GROUP BY Customer_ID 
ORDER BY Updated_timestamp DESC LIMIT 1);

答案 2 :(得分:0)

使用rowid伪列。

var fileName = @"d:\1.xlsx"; var connectionString = string.Format( "Provider=Microsoft.Jet.OLEDB.4.0; data source="+fileName+ "; Extended Properties=Excel 8.0;", fileName); var adapter = new OleDbDataAdapter("SELECT * FROM [sheet1$]", connectionString); var ds = new DataSet(); adapter.Fill(ds, "anyNameHere"); DataTable data = ds.Tables["anyNameHere"];

其中column1,column2和column3组成每条记录的标识键。您可以列出所有列。