0

我需要帮助解决一个困难的查询。这与在 Spree Commerce 平台中实施优惠券的复杂方式有关。

我只需要未付优惠券的总金额。

这些表是:

优先

id | value  | key
---+---------------------------------------------
1  | 25     | spree/calculator/flat_rate/amount/5

计算器

id  | calculable_id | calculable_type
----+---------------+-----------------
5   | 3             | promotion_action

促销活动

id  | activator_id  
----+-------------
3   | 2

活化剂

id | expires_at | usage_limit 
---+------------+------------
2  | 2013-12-01 | 4           

调整

originator_type  | originator_id | amount
-----------------+---------------+-------
promotion_action | 3             | -25

preference.key 中的最后一个数字对应于计算器的 id。

首先我需要总的preferences.amount,乘以activators.usage_limit(除非activators.expires_at <今天),其中preferences.key LIKE '%calculator/flat_rate%'。

结果应该是这个金额减去相应调整的总和。金额

我做到了

select 
 (select sum(value) from spree_preferences 
   where `key` like "%calculator/flat_rate%") 
 + 
 (select sum(amount) from spree_adjustments 
   where originator_type = 'promotion_action') as total;

, 但这没有考虑 expires_at 和 usage_limit。

对于更新的狂欢,答案如下:

select sum(subAggregate.outstanding) from ( select (subDetail.value * subDetail.multiplier) + subDetail.adjustmentAmount as outstanding from ( select p.value, case when a.expires_at > curDate() then a.usage_limit else 1 end as multiplier , ifNull(adj.amount,0) as adjustmentAmount from spree_preferences p left outer join spree_calculators c on replace(p.key,'spree/calculator/flat_rate/amount/','') = c.id left outer join spree_promotion_actions pa on c.calculable_id = pa.id and c.calculable_type = 'Spree::PromotionAction' left outer join spree_promotions a on pa.promotion_id = a.id left outer join spree_adjustments adj on pa.id = adj.source_id and pa.type = 'Spree::PromotionAction' ) subDetail ) subAggregate

4

1 回答 1

2
select sum(subAggregate.outstanding)
from
    (
    select (subDetail.value * subDetail.multiplier) + subDetail.adjustmentAmount as outstanding
    from
        (
        select  p.value,
                case
                    when a.expires_at > curDate() then a.usage_limit
                    else 1
                end as multiplier ,
                ifNull(adj.amount,0) as adjustmentAmount
        from    preferences p
                left outer join calculators c
                    on replace(p.key,'spree/calculator/flat_rate/amount/','') = c.id
                left outer join promotion_actions pa
                    on c.calculabel_id = pa.id
                    and c.calculable_type = 'promotion_action'
                left outer join activators a
                    on pa.activator_id = a.id
                left outer join adjustments adj
                    on pa.id = adj.originator_id
                    and pa.originator_type = 'promotion_action'
        ) subDetail
    ) subAggregate
于 2013-04-03T14:52:54.047 回答