2
customers:
+------------+--------------+ 
| cid        | Name         | 
+------------+--------------+ 
| 1          | Bob          |
| 2          | John         | 
| 3          | Jane         | 
+------------+--------------+ 
accounts:
+------------+--------------+ 
| aid        | type         | 
+------------+--------------+ 
| 1          | Checking     |
| 2          | Saving       | 
| 3          | CD           | 
+------------+--------------+ 
transactions:
+------------+--------------+--------------+ 
| tid        | cid          | aid          | 
+------------+--------------+--------------+ 
| 1          | 1            | 1            | 
| 2          | 2            | 1            | 
| 3          | 1            | 2            | 
| 4          | 2            | 3            | 
| 5          | 3            | 1            | 
+------------+--------------+--------------+

我正在尝试编写一个 plsql 程序,给定客户 ID 作为参数,将显示他/她的 ID、姓名和所有帐户。显示 id 和 name 很简单。我不确定的是如何获取链接到客户 ID 的所有帐户以及如何检索多个帐户。

4

1 回答 1

0

一个想法可以是:

select c.cid, c.name, a.type
from customers c
left join transactions t on (t.cid = c.cid)
left join accounts a on (a.aid = t.aid)
where c.cid = :customer_id
group by c.cid, c.name, a.type;

group by 是必需的,因为可以是更多事务。

此外,如果您想查看一行:

select cid, name, LISTAGG(type, ',') WITHIN GROUP (ORDER BY type) as account_types
from(
    select distinct c.cid, c.name, a.type
    from customers c
    left join transactions t on (t.cid = c.cid)
    left join accounts a on (a.aid = t.aid)
    where c.cid = :customer_id

)
group by cid, name;

把它放到一个存储过程/函数中太简单了,所以我把它交给你。

于 2012-12-05T07:18:26.983 回答