【问题标题】:Oracle - select statement to rollup multiple tables within a time frameOracle - 选择语句在一个时间范围内汇总多个表
【发布时间】:2016-12-13 02:44:32
【问题描述】:

我有 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

【问题讨论】:

  • 您希望输出是什么?请用所需的结果编辑问题。
  • 为什么一个客户会在一次交易中出现多次?

标签: sql oracle transactions


【解决方案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;

【讨论】:

  • 对不起!那是错误的!我不认为这是考虑到 1 周的时间段?
  • @AAA 。 . .正如我在答案中解释的那样,您需要加入transactions 表,但您的问题没有指定实际时间段。
  • 交易一周... I.E.交易 4,5,6 在 1 周内
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-16
  • 2012-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多