删除重复行有null

时间:2017-04-16 21:09:37

标签: sql oracle

这是数据

Id Name Value col1 col2 col3
1  test1 1    null null null
2  test1 1    x    null null
3  test1 1    x    y    null
4  test2 2    x    y    z
5  test2 2    x    y    null

根据"姓名"查找重复内容和"价值"列并删除在更多列中具有空值的那个。

我设法通过关注http://www.dba-oracle.com/t_delete_duplicate_table_rows.htm#null来删除重复项,但dint知道在SQL中应该做些什么来实现这一点

预期结果

ID Name Value col1 Col2 Col3
3  test1  1   X     y    null
4  test2  2   x     y    z

1 个答案:

答案 0 :(得分:1)

Oracle安装程序

$posts = Category::where('category_name','=',$categoryName)->first()->posts;

<强>查询

CREATE TABLE table_name ( Id, Name, Value, col1, col2, col3 ) AS
SELECT 1,  'test1', 1,    null, null, null FROM DUAL UNION ALL
SELECT 2,  'test1', 1,    'x',  null, null FROM DUAL UNION ALL
SELECT 3,  'test1', 1,    'x',  'y',  null FROM DUAL UNION ALL
SELECT 4,  'test2', 2,    'x',  'y',  'z'  FROM DUAL UNION ALL
SELECT 5,  'test2', 2,    'x',  'y',  null FROM DUAL;

<强>输出

SELECT *
FROM   (
  SELECT t.*,
         ROW_NUMBER() OVER (
           PARTITION BY name, value
           ORDER BY DECODE( col1, NULL, 0, 1 )
                      + DECODE( col2, NULL, 0, 1 )
                      + DECODE( col3, NULL, 0, 1 ) DESC,
                    col1, col2, col3
         ) AS rn
  FROM   table_name t
)
WHERE  rn = 1;