我有一个项目的3个Oracle表,它将演示事务表链接到Transaction_Customer和Transaction_Employee,如下所示。每笔交易都涉及多个客户,涉及许多员工。
我正在尝试编写一个SQL查询,该查询将列出在一个时间段内与多个员工进行交易的每个Customer_ID。我希望输出为每个Customer_ID包含一行,并使用逗号分隔的列表,其中Employee_ID与该客户进行了交易。
输出应如下所示:
Customer_ID|Employees
601|007,008,009
将表连接在一起的基本查询如下所示:
select * from transactions t
left join transactions_customer tc
on t.t_id = tc.t_id
left join transactions_employee te
on t.t_id = te.t_id
如何完成此操作我是否完成了此任务并使查询以预期的方式运行?
谢谢!
交易
T_ID|Date|Amount
1|1/10/2017|100
2|1/10/2017|200
3|1/31/2017|150
4|2/16/2017|175
5|2/17/2017|175
6|2/18/2017|185
Transactions_Customer
T_ID|Customer_ID
1|600
1|601
1|602
2|605
3|606
4|601
5|607
6|607
Transactions_Employee
T_ID|Employee_ID
1|007
1|008
2|009
3|008
4|009
5|007
6|007
答案 0 :(得分:1)
这是你想要的吗?
select tc.Customer_id,
listagg(te.employee_id, ',') within group (order by te.employee_id) as employees
from Transactions_Customer tc join
Transactions_Employee te
on tc.t_id = te.t_id
group by tc.Customer_id;
您只需要Transactions
表来过滤日期。你的问题暗示了这种过滤,但没有完全描述它,所以我把它遗漏了。
编辑:
客户数据(也可能是员工数据)也有重复数据。要在输出中避免这些:
select tc.Customer_id,
listagg(te.employee_id, ',') within group (order by te.employee_id) as employees
from (select distinct tc.t_id, tc.customer_id
from Transactions_Customer tc
) tc join
(select distinct te.t_id, te.employee_id
from Transactions_Employee te
) te
on tc.t_id = te.t_id
group by tc.Customer_id;