删除另一行

时间:2016-03-08 11:37:50

标签: sql oracle oracle10g

我在表test2中有以下数据

enter image description here

我想要实现的是通过删除表的任何列中的重复值来检索一行,这意味着消除另一行的重复或重复值并产生一行。

数据库版本是Oracle 10g。

预期输出

enter image description here

表结构和数据

CREATE TABLE test2
(
   supplier_id        VARCHAR2 (256),
   supplier_name      VARCHAR2 (256),
   supplier_country   VARCHAR2 (256),
   contact_name       VARCHAR2 (256),
   address            VARCHAR2 (256)
);


SET DEFINE OFF;
Insert into TEST2
   (SUPPLIER_ID, SUPPLIER_NAME, SUPPLIER_COUNTRY, CONTACT_NAME, ADDRESS)
 Values
   ('IS230856', 'XYZ Inc.', 'U.S.', 'Jones', 'P.O. Box 2354');
Insert into TEST2
   (SUPPLIER_ID, SUPPLIER_NAME, SUPPLIER_COUNTRY, CONTACT_NAME, ADDRESS)
 Values
   ('IS230856', 'XYZ Inc.', 'U.S.', 'James', 'P.O. Box 2358');
Insert into TEST2
   (SUPPLIER_ID, SUPPLIER_NAME, SUPPLIER_COUNTRY, CONTACT_NAME, ADDRESS)
 Values
   ('IS230856', 'XYZ Inc.', 'U.S.', 'James', 'P.O. Box 2354');
Insert into TEST2
   (SUPPLIER_ID, SUPPLIER_NAME, SUPPLIER_COUNTRY, CONTACT_NAME, ADDRESS)
 Values
   ('IS230856', 'XYZ Inc.', 'U.S.', 'Jones', 'P.O. Box 2358');
Insert into TEST2
   (SUPPLIER_ID, SUPPLIER_NAME, SUPPLIER_COUNTRY, CONTACT_NAME, ADDRESS)
 Values
   ('IS230856', 'XYZ Inc.', 'U.S.', 'Smith', 'P.O. Box 2354');
COMMIT;

2 个答案:

答案 0 :(得分:1)

Oracle安装程序

CREATE TYPE VARCHAR2s_Table AS TABLE OF VARCHAR2(4000);

CREATE FUNCTION to_String(
  p_strings VARCHAR2s_Table,
  p_delim   VARCHAR2        DEFAULT ','
)
RETURN VARCHAR2
IS
  o_str VARCHAR2(4000);
BEGIN
  IF p_strings IS NULL OR p_strings IS EMPTY THEN
    RETURN NULL;
  END IF;
  o_str := p_strings(1);
  FOR i IN 2 .. p_strings.COUNT LOOP
    o_str := o_str || p_delim || p_strings(i);
  END LOOP;
  RETURN o_str;
END;
/

<强>查询

SELECT supplier_id,
       supplier_name,
       supplier_county,
       TO_STRING( SET( CAST( COLLECT( contact_name ) AS VARCHAR2s_Table ) ) )
         AS contact_names,
       TO_STRING( SET( CAST( COLLECT( address ) AS VARCHAR2s_Table ) ) )
         AS addresses
FROM   test2
GROUP BY supplier_id,
       supplier_name,
       supplier_county;

答案 1 :(得分:0)

您可以使用ORACLE的listagg:

SELECT t.supplier_ID,t.supplier_name,t.supplier_country,
       listagg(t.contact_name,',') within group(order by t.contact_name),
       listagg(t.address,',') within group(order by t.address)
FROM TEST2 t
GROUP BY  t.supplier_ID,t.supplier_name,t.supplier_country