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)
    

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...