如何删除SQL Server中的重复序列号?

时间:2015-06-24 00:01:23

标签: sql sql-server-2012

我在SQL Server 2012中有一个BOM表。我需要删除一些中间层,因为它们具有相同的序列号。以下是当前状态和期望结果的结构。有人可以帮助提供SQL查询或过滤逻辑吗?请参阅封闭图像以获取格式化表格。

现状:

Parent #    Child # Parent Name     Child Name 
----------------------------------------------
123        123  Sale SKU    Sale SKU
123        123  Sale SKU    PC Pack
123        123  PC Pack        Device
123        456  Device          LCD
123        789  Device           Kit

期望状态:

Parent #    Child #     Parent Name     Child Name 
--------------------------------------------------
123         123         Sale SKU        Sale SKU
123         456         Sale SKU        LCD
123         789         Sale SKU        Kit

格式化表格:

http://i.stack.imgur.com/kBN5D.png

2 个答案:

答案 0 :(得分:1)

您没有说过您正在使用的DBMS,所以这里是删除行的oracle解决方案:

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE TEST ( Parent, Child,  Parent_Name, Child_Name ) AS
          SELECT 123, 123, 'Sale SKU', 'Sale SKU' FROM DUAL
UNION ALL SELECT 123, 123, 'Sale SKU', 'PC Pack' FROM DUAL
UNION ALL SELECT 123, 123, 'PC Pack',  'Device' FROM DUAL
UNION ALL SELECT 123, 456, 'Device',   'LCD' FROM DUAL
UNION ALL SELECT 123, 789, 'Device',   'Kit' FROM DUAL;

DELETE FROM TEST
WHERE ROWID IN (
  SELECT ROWID
  FROM   (
    SELECT ROW_NUMBER() OVER ( PARTITION BY Parent, Child ORDER BY NULL ) AS RN
    FROM   TEST
  )
  WHERE  RN > 1
);

查询1

SELECT * FROM TEST

<强> Results

| PARENT | CHILD | PARENT_NAME | CHILD_NAME |
|--------|-------|-------------|------------|
|    123 |   123 |    Sale SKU |   Sale SKU |
|    123 |   456 |      Device |        LCD |
|    123 |   789 |      Device |        Kit |

答案 1 :(得分:1)

不确定您使用的是哪个RDBMS,但如果它stopTimer,那么您可以使用ROW_NUMBER()函数来获取所需的数据,例如

SQL SERVER