连接不同的字符串和数字

Concatenate distinct strings and numbers

我正在尝试获取一个不同的 employee_id 串联列表,并对它们的 employee_allowance 求和。但是,我不想对重复的 employee_idemployee_allowance.

求和

我的预期结果

name employee_ids allowance this column is for explanation (not part of output)
Bob 11Bob532, 11Bob923 26 13+13=26 because the id's are different, so we sum both
Sara 12Sara833 93
John 18John243, 18John823 64 21+43=64 because we got rid of the duplicate 18John243's allowance

Tablecreation/dummy数据

CREATE TABLE emp (
   name varchar2(100) NOT NULL,
   employee_id varchar2(100) NOT NULL,
   employee_allowance number not null
);

INSERT INTO emp (name, employee_id, employee_allowance) VALUES ('Bob', '11Bob923', 13);
INSERT INTO emp (name, employee_id, employee_allowance) VALUES ('Bob', '11Bob532', 13);
INSERT INTO emp (name, employee_id, employee_allowance) VALUES ('Sara', '12Sara833', 93);
INSERT INTO emp (name, employee_id, employee_allowance) VALUES ('John', '18John243', 21);
INSERT INTO emp (name, employee_id, employee_allowance) VALUES ('John', '18John243', 21);
INSERT INTO emp (name, employee_id, employee_allowance) VALUES ('John', '18John823', 43);

我的尝试

我的输出给出了不同的、串联的 employee_ids,但仍然总结了重复的 employee_allowance 行。

SELECT
  name,
  LISTAGG(DISTINCT employee_id, ', ') WITHIN GROUP (ORDER BY employee_id) "ids",
  SUM(employee_allowance)
FROM emp
GROUP BY
  name

首先找到 DISTINCT 行然后聚合:

SELECT name,
       LISTAGG(employee_id, ', ')  WITHIN GROUP (ORDER BY employee_id) AS employee_ids,
       SUM(employee_allowance) AS allowance
FROM   (
  SELECT DISTINCT *
  FROM   emp
)
GROUP BY name

其中,对于示例数据,输出:

NAME EMPLOYEE_IDS ALLOWANCE
Bob 11Bob532, 11Bob923 26
John 18John243, 18John823 64
Sara 12Sara833 93

db<>fiddle here