如何解决PL / SQL-Oracle 9.1
| 这是我们正在此处处理的方案。我们有一个客户表和一个销售表。这些表通过客户表中的事务ID联接。 顾客可以从商店购买任何水果。 例如,我们需要做的是找出:多少顾客在购买樱桃之前就购买了苹果。Table structure:
Cust - Cust ID,Transaction ID,...
Sales - Transaction ID,Fruit ID,Insert date for record,...
考虑到客户可能会多次购买水果,因此同一水果ID可能具有不同的交易ID,这是实现此目标的最经济高效的方式。
因此,我们需要查找客户何时购买了第一苹果和第一樱桃,然后检查它们的日期。
解决方法
我赞同加里对数据模型的看法,但这与问题无关。
这是一种可能的解决方案。如果FRUIT_ID的潜在值很多并且该列已建立索引,则可能会非常有效。
select apple.cust_id
from
( select c.cust_id,min(s.sale_date) as sale_date
from cust c
join sales s
on s.transaction_id = c.transaction_id
where s.fruit_id = \'CHERRY\'
group by c.cust_id ) cherry,( select c.cust_id,min(s.sale_date) as sale_date
from cust c
join sales s
on s.transaction_id = c.transaction_id
where s.fruit_id = \'APPLE\'
group by c.cust_id ) apple
where cherry.cust_id = apple.cust_id
and cherry.sale_date > apple.sale_date
/
如果FRUIT_ID的值较少,那么对Gary的建议进行修改可能会更有效:
select cust_id
from
( select c.cust_id,min(case when s.fruit_id = \'CHERRY\' = s.sale_date else null end) as cherry_date,min(case when s.fruit_id = \'APPLE\' = s.sale_date else null end) as apple_date
from cust c
join sales s
on s.transaction_id = c.transaction_id
group by c.cust_id ) cherry
where cherry_date > apple_date
/
警告:我目前无法访问数据库,因此这些语句未经测试,可能存在语法错误。如果可以的话,我会检查的。
,transaction_id如何成为客户的列/属性?这意味着客户只能进行一次交易。
假设您有一个包含customer_id,fruit_id和sale_date的表,则可以尝试
select cust_id,min(case when fruit_id = \'Apple\' then sale_date end) first_apple_purchase,min(case when fruit_id = \'Cherry\' then sale_date end) first_cherry_purchase
from transactions
group by cust_id
having min(case when fruit_id = \'Apple\' then sale_date end) <
min(case when fruit_id = \'Cherry\' then sale_date end)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。