【问题标题】:Grouping multile SQL results by a given field按给定字段对多个 SQL 结果进行分组
【发布时间】:2015-09-21 22:25:24
【问题描述】:

如何按员工对以下查询的结果进行分组?

好的,所以我有三个表: 1. company_employee,其中包含映射到公司 ID (company.id) 的员工 ID (company_employee.employee)。它还包含一个员工角色

  1. 包含员工名字、姓氏的员工

  2. 包含 id 和名称的公司

现在,我正在检索具有特定角色的所有员工,但我获得了同一员工的多个条目,具有不同的公司映射。像这样的东西: 我的查询是:

SELECT company_employee.employee, company_employee.company, employee.fname, employee.lname, company.name
 FROM company_employee
 JOIN employee on employee.id = company_employee.employee
 JOIN company on company.id = company_employee.company
 WHERE company_employee.role= 185;

我的结果是:

company_employee.employee     company_employee.company     employee.fname     employee.lname    company.name
111                           100                          John               Smith             Super Candy
111                           101                          John               Smith             Red Ballons
222                           102                          Kevin              Lora              Super Computers
111                           103                          John               Smith             Star Events
222                           104                          Kevin              Lora              Vintage Pencils
333                           105                          Margarett          Bush              Top Security

我想要的是这样一个列表:

Employee 111 John Smith mapped to a list of companies (100, 101, 103)
Employee 222 Kevin Lora mapped to a list of companies (102, 104)
Employee 333 Margarett Bush mapped to a list of companies (105)

这可能吗?

【问题讨论】:

  • 您能否分享您尝试获取此数据的确切结果?
  • 我不想把实际的客户数据放在这里。我不想以多个员工条目结束。我想要每个员工的条目,但每个条目都包含其关联公司的列表。

标签: sql database oracle database-schema


【解决方案1】:

您似乎正在寻找listagg 函数:

SELECT   company_employee.employee, employee.fname, employee.lname, 
         LISTAGG(company_employee.company) 
           WITHIN GROUP (ORDER BY company_employee.company),
         LISTAGG(company.name) 
           WITHIN GROUP (ORDER BY company_employee.company),
FROM     company_employee
JOIN     employee ON employee.id = company_employee.employee
JOIN     company ON company.id = company_employee.company
WHERE    company_employee.role = 185
GROUP BY company_employee.employee, employee.fname, employee.lname

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2012-05-21
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多