复杂的子查询wihtin CASE语句

时间:2017-08-24 17:42:13

标签: mysql sql subquery case correlated-subquery

我有这个查询,根据用户获取的“渠道”,“id_store”和用户的“国家/地区”计算收据的预期价值。

生成的查询包含此列。

计数| id_store |国家| price_usd |渠道| T2S |预期收入| ExpectedRevenue_projections

(注意:ExpectedRevenue = count * price_usd * T2S)

在此查询中,我想知道8月购买并在9月到期的那些收据的价值(这些产品有试用期,我们根据历史转换率计算其价值(试用2订阅又称T2S) ))。

当我们没有某些情景的历史数据时会出现问题;要么我们开始与id_stores,新国家,渠道或先前的任何组合出售不同,T2S变为'null'值,列'ExpectedRevenue'因此具有'null'值'--->这就是为什么我有一个'CASE'函数让T2S取值'。28'每当发生这种情况时我只需将“ExpectedRevenue_projections”列加起来以获得最终结果

然而,这个'。28'只是一个根本不准确的固定值(我们有10到120美元的产品......)。

这就是为什么我要求亲爱的stackoverflow贡献者为另一个T2S替换这个'28%',在这种情况下,这个T2S将根据'country'和'price_usd'间隔(例如(0-15))来历史计算,( 15.01-29.99),(30 - 49.99)......等等。

(放置区间的原因是'price_usd'是根据创建时的汇率计算的,因此客户以外币购买的相同产品可能是49.99,49.98,49.97 ......和T2S如果没有历史数据,它将变为“空”。

谢谢

SELECT
r.count AS count,
r.id_store AS id_store,
r.country AS country,
r.price_usd AS price_usd,
r.channel AS channel,

a.count / (a.count + u.count) AS T2S,    
r.count * r.price_usd * (a.count / (a.count + u.count)) AS ExpectedRevenue,


CASE WHEN (a.count / (a.count + u.count)) is null then (r.count * r.price_usd * .28) else r.count * r.price_usd * (a.count / (a.count + u.count)) END AS ExpectedRevenue_projections



FROM
(
select count(distinct(r.user_id)) AS count, p.id_store, u.country, r.price_usd, channel
from receipts as r 
    inner join products as p on p.id=r.product_id 
    inner join customers as c on r.customer_id=c.id 
    inner join users as u on u.id=r.user_id
where 
    MONTH(DATE_ADD(DATE_ADD(r.original_subscription_at, INTERVAL p.trial_days DAY), INTERVAL p.trial_months MONTH)) = 9
    and YEAR(original_subscription_at) = 2017
    and MONTH(original_subscription_at) = 8
    and YEAR(r.expiration_at) = 2017
    and MONTH(r.expiration_at) = 9


    and r.status='trial'
    and p.platform not in ('manual')
    and c.tester=0
group by 2,3,4,5
) AS r

LEFT JOIN
(
select count(distinct r.user_id) AS count, u.country, p.id_store, channel
from receipts as r 
    inner join products as p on p.id=r.product_id
    inner join users as u on u.id=r.user_id
where year(r.created_at)=2017
    AND r.status = 'active'
group by 2,3,4
) AS a

ON r.country = a.country AND r.id_store = a.id_store AND r.channel = a.channel

LEFT JOIN
(
select count(distinct r.user_id) AS count, u.country, p.id_store, channel
from receipts as r 
    inner join products as p on p.id=r.product_id
    inner join users as u on u.id=r.user_id
where year(r.created_at)=2017
    AND r.status = 'unpaid'
group by 2,3,4
) AS u
ON r.country = u.country AND r.id_store = u.id_store AND r.channel = u.channel

0 个答案:

没有答案
相关问题