[英]Use the result of a sub-query outside of the sub-query
我有一个这样结构的表。
用户身份 | 订阅类型 | 时间戳 |
---|---|---|
100 | 支付中 | 2/10/2021 |
99 | 审判 | 2/10/2021 |
100 | 审判 | 15/9/2021 |
我希望我的 output 保持不变,当订户转换为付费订阅时,增加一个列来提取试用开始日期。
用户身份 | 订阅类型 | 时间戳 | 试用_开始_日期 |
---|---|---|---|
100 | 支付中 | 2/10/2021 | 15/9/2021 |
99 | 审判 | 2/10/2021 | |
100 | 审判 | 2/10/2021 |
目前,我有这个查询:
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
我有一条关于 se1 的错误信息。 未定义timestamp
。 我明白为什么,但我看不到解决方法。
任何指针?
如果您需要从子查询中获取两个值,则必须将其连接起来,而不是将其用作表达式。
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
非常感谢。 由于某些原因,我需要在 SELECT 中明确声明 GROUP BY 中使用的变量。 不知道为什么(我使用的是 MySQL5.7,所以可能与此相关),无论如何。 这是工作查询。
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.