在子查询外使用子查询的结果

Use the result of a sub-query outside of the sub-query

我有一个 table 结构是这样的。

User_id Subscription_type timestamp
100 PAYING 2/10/2021
99 TRIAL 2/10/2021
100 TRIAL 15/9/2021

我希望我的输出是相同的,当订阅者转换为付费订阅时,增加一个列来提取试用开始日期。

User_id Subscription_type timestamp Trial_Start_date
100 PAYING 2/10/2021 15/9/2021
99 TRIAL 2/10/2021
100 TRIAL 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