[英]Use the result of a sub-query outside of the sub-query
I have a table structured like this.我有一个这样结构的表。
User_id用户身份 | Subscription_type订阅类型 | timestamp时间戳 |
---|---|---|
100 100 | PAYING支付中 | 2/10/2021 2/10/2021 |
99 99 | TRIAL审判 | 2/10/2021 2/10/2021 |
100 100 | TRIAL审判 | 15/9/2021 15/9/2021 |
I want my output to be the same, with an additional column pulling the trial start date when the subscriber converts to a paying subscription.我希望我的 output 保持不变,当订户转换为付费订阅时,增加一个列来提取试用开始日期。
User_id用户身份 | Subscription_type订阅类型 | timestamp时间戳 | Trial_Start_date试用_开始_日期 |
---|---|---|---|
100 100 | PAYING支付中 | 2/10/2021 2/10/2021 | 15/9/2021 15/9/2021 |
99 99 | TRIAL审判 | 2/10/2021 2/10/2021 | |
100 100 | TRIAL审判 | 2/10/2021 2/10/2021 |
At the moment, I have this query:目前,我有这个查询:
SELECT *,
CASE WHEN
(SELECT `subscription_type` FROM subscription_event se1
WHERE se1.`timestamp` < se.`timestamp` AND se1.user_id = se.user_id
ORDER BY user_id DESC LIMIT 1) = 'TRIAL'
then se1.`timestamp` else 0 end as "Converted_from_TRIAL"
FROM subscription_event se
I have an error message with se1.我有一条关于 se1 的错误信息。 timestamp
not been defined.未定义timestamp
。 I understand why, but I cannot see a workaround.我明白为什么,但我看不到解决方法。
Any pointer?任何指针?
If you need to get two values out of the subquery, you have to join with it, not use it as an expression.如果您需要从子查询中获取两个值,则必须将其连接起来,而不是将其用作表达式。
SELECT se.*,
MAX(se1.timestamp) AS Converted_from_TRIAL
FROM subscription_event AS se
LEFT JOIN subscription_event AS se1 ON se.user_id = se1.user_id AND se1.timestamp < se.timestamp AND se1.subscription_type = 'TRIAL'
GROUP BY se.user_id, se.subscription_type, se.timestamp
Thanks a lot.非常感谢。 For some reasons I needed to declare explicitely in SELECT the variables used in the GROUP BY.由于某些原因,我需要在 SELECT 中明确声明 GROUP BY 中使用的变量。 Not sure why ( I am using MySQL5.7 so maybe it is linked with that), In any case.不知道为什么(我使用的是 MySQL5.7,所以可能与此相关),无论如何。 this is the working query.这是工作查询。
SELECT se.user_id, se.subscription_type, se.timestamp,
MAX(se1.timestamp) AS Converted_from_TRIAL
FROM subscription_event AS se
LEFT JOIN subscription_event AS se1 ON se.user_id = se1.user_id AND se1.timestamp < se.timestamp AND se1.subscription_type = 'TRIAL'
GROUP BY se.user_id, se.subscription_type, se.timestamp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.