简体   繁体   English

Oracle在多个列中使用ListAgg,不同的值

[英]Oracle Using ListAgg, distinct values, across multiple columns

for Oracle 12c... I have a table of line items sold to a company. 对于Oracle 12c ...我有一张出售给某公司的行项目表。 This table has a 3-tier level hierarchy of the rep who sold to this company. 该表具有销售给该公司的代表的3层级别层次结构。 One of the columns is the company name. 列之一是公司名称。 I need help writing the SQL to generate a comma separated, unique list of the names of ALL the people, across all three columns, across all rows sold to this company. 我需要编写SQL的帮助,才能生成逗号分隔的唯一名称列表,该列表包含所有三列,出售给该公司的所有行中所有人员的姓名。 For an example... 举个例子...

CompanyName  Rep      Manager     GVP
-----------  -------  --------   --------
Sears        Bob      Tim        Frank
Sears        Jack     Tim        Frank
Ace          Scott    Chris      Bill

When I look at Sears, the SQL should return 'Bob, Jack, Tim, Frank'. 当我查看Sears时,SQL应该返回“ Bob,Jack,Tim,Frank”。 The ORDER of the names does NOT matter, only that they are unique, and that they include names from all 3 fields. 名称的ORDER无关紧要,只是它们是唯一的,并且它们包括来自所有3个字段的名称。 I would assume that this is a type of ListAgg query, but could be wrong... 我认为这是ListAgg查询的一种,但可能是错误的...

Use the UNPIVOT operator (it will only do a single table scan whereas using UNION will typically do one table scan for each SELECT in the unioned statement): 使用UNPIVOT符(它将仅执行单个表扫描,而使用UNION通常将对联合语句中的每个SELECT执行一个表扫描):

Oracle Setup : Oracle安装程序

CREATE TABLE table_name ( CompanyName, Rep, Manager, GVP ) AS
SELECT 'Sears', 'Bob',   'Tim',   'Frank' FROM DUAL UNION ALL
SELECT 'Sears', 'Jack',  'Tim',   'Frank' FROM DUAL UNION ALL
SELECT 'Ace',   'Scott', 'Chris', 'Bill'  FROM DUAL;

Query : 查询

SELECT CompanyName,
       LISTAGG( Name, ',' ) WITHIN GROUP ( ORDER BY Name ) AS Names
FROM   (
  SELECT DISTINCT
         CompanyName,
         Name
  FROM   table_name
  UNPIVOT( name FOR typ IN ( Rep, Manager, GVP ) )
)
GROUP BY CompanyName;

Output : 输出

COMPANYNAME NAMES
----------- ------------------
Ace         Bill,Chris,Scott
Sears       Bob,Frank,Jack,Tim

You need to unpivot the data (to remove duplicates) and then reaggregate it: 您需要取消数据透视表(删除重复项),然后重新汇总:

select companyname, listagg(person, ',') within group (order by person) as persons
from ((select companyname, repfrom as person t) union
      (select companyname, manager from t) union
      (select companyname, gvp from t)
     ) t
group by companyname;

This SQL should do the trick: 此SQL应该可以解决问题:

select listagg(p, ', ') within group (order by p) from (
  select rep p
  from   your_table
  union
  select manager p
  from   your_table
  union
  select gvp p
  from   your_table);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM