复杂案例陈述问题 - Oracle SQL

时间:2016-10-27 02:10:57

标签: sql oracle

写下面的查询,但是得到倍数,因为聚合需要在case语句之前发生。会喜欢一些建议的最佳方法。

FooBar

1 个答案:

答案 0 :(得分:2)

这是你可以做到的一种方式:

SELECT cust.store,
       cust.custid,
       cust.id_cust,
       gift.giftamt,
       gift.custgift,
       cpn.couponamt,
       sprt.sportsamt
FROM   cust
       LEFT OUTER JOIN (SELECT id_cust,
                               SUM(CASE WHEN cg.code_status = 'C' AND gi.flag_store_loc = 'N' THEN cg.amt_paid END) giftamt,
                               SUM(CASE WHEN cg.code_status = 'C' AND gi.flag_store_loc = 'Y' THEN cg.amt_paid END) custgiftamt
                        FROM   cust_gift cg
                               INNER JOIN gift_item gi ON cg.id_gift_item = gi.id_gift_item) gift ON cust.id_cust = gift.id_cust
       LEFT OUTER JOIN (SELECT id_cust,
                               SUM(CASE WHEN code_status = 'C' THEN amt END) couponamt
                        FROM   cust_coupon) cpn ON cust.id_cust = cpn.id_cust
       LEFT OUTER JOIN (SELECT id_cust,
                               SUM(CASE WHEN status = 'C' THEN amt END) sportsamt
                        FROM   cust_sports) sprt ON cust.id_cust = sprt.id_cust
WHERE  (STORE = 'M669098' OR STORE = 'M66923434');