这是我们正在此处处理的方案。我们有一个客户表和一个销售表。这些表通过客户表中的事务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
/
警告:我目前无法访问数据库,因此这些语句未经测试,可能存在语法错误。如果可以的话,我会检查的。
关于sql - PL/SQL-Oracle 9.1,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6131955/