如何选择不同的项目而不必在group by子句中使用?

时间:2018-07-09 11:29:49

标签: sql oracle

我正在尝试使用类似SQL的方法在某些列中找到sum

      select   distinct  c.customer,
       c.customer_id,
       sum(d.delay) as delay,
       sum(d.delayed_amount) as delay_amt,
       pd.product

  from product pd
  inner join mfg_company mfg on pd.product_id=mfg.product_id
  inner join store s on mfg.store_id = s.store_id
  inner join customer c on s.customer = c.customer_id
  join delay_detail d on pd.product_id = d.material
 where d.product_mfg_id = 466
 group by c.customer,customer_id
 order by c.customer,c.customer_id

问题是mfg_company具有重复的product_id(多个映射),因此,当我尝试查找sum时,它也包括这些重复项。 在group by子句中使用product_id对我想看到的结果没有帮助。那么如何仅在不同的product_id上联接?

2 个答案:

答案 0 :(得分:0)

我认为解决您的问题的方法是预先汇总延迟。尚不清楚是否要在结果集中使用该产品。假设您不这样做:

select c.customer, c.customer_id,
       sum(d.delay) as delay, sum(d.delay_amt) as delay_amt
from product pd join
     mfg_company mfg
     on pd.product_id = mfg.product_id join
     store s
     on mfg.store_id = s.store_id
     customer c
     on s.customer = c.customer_id join
     (select d.material, sum(d.delay) as delay, sum(d.delayed_amount) as delay_amt
      from delay_detail d
      group by d.material
     ) d
     on pd.product_id = d.material
where d.product_mfg_id = 466
group by c.customer, customer_id
order by c.customer, c.customer_id;

请注意,几乎不需要将select distinctgroup by一起使用。

答案 1 :(得分:0)

如果有帮助,您可以尝试下面的查询-

 select distinct c.customer
                ,c.customer_id
                ,sum(d.delay) as delay
                ,sum(d.delayed_amount) as delay_amt
                ,pd.product
 from product pd
 inner join (select distinct product_id
                            ,store_id
             from mfg_company) mfg on pd.product_id=mfg.product_id
 inner join store s on mfg.store_id = s.store_id
 inner join customer c on s.customer = c.customer_id
 join delay_detail d on pd.product_id = d.material
 where d.product_mfg_id = 466
 group by c.customer,customer_id
 order by c.customer,c.customer_id