mysql 尝试按顺序对行进行排名

mysql trying to rank rows by order by

我想计算我的行的排序排名。它计算不正确 - 我只得到一个 null 和 1。我希望得到 1、2、3 的排名......基于我的 joins/order by ladder_name_lh2 = ladder_name_lh1 和 date_trigger_event_lh2,以及 member_id_lh1。

基本上,我想说的是 如果 ladder_name_2 匹配 ladder_name_1(这是一个 before/after 设置 - 阶梯 2 在阶梯 1 之后,并且有 6 个阶梯名称(类别),但为了表明它们是相关的,我想确保只有在匹配前后的类别时才会生成排名),然后根据 date_2、member_id 生成排名。

我写了以下内容:

select 
        cte_ladder_history_self_join_lh1.member_id_lh1,
        cte_ladder_history_self_join_lh1.ladder_config_id_lh1,
        cte_ladder_history_self_join_lh1.trigger_name_lh1,
        cte_ladder_history_self_join_lh1.trigger_record_id_lh1,
        cte_ladder_history_self_join_lh1.date_trigger_event_lh1,
        cte_ladder_history_self_join_lh1.ladder_name_lh1,
        cte_ladder_history_self_join_lh1.ladder_value_lh1,
        cte_ladder_history_self_join_lh1.ladder_change_lh1,
        cte_ladder_history_self_join_lh2.member_id_lh2,
        cte_ladder_history_self_join_lh2.trigger_name_lh2,
        cte_ladder_history_self_join_lh2.trigger_record_id_lh2,
        cte_ladder_history_self_join_lh2.date_trigger_event_lh2,
        cte_ladder_history_self_join_lh2.ladder_name_lh2,
        cte_ladder_history_self_join_lh2.ladder_value_lh2,
        cte_ladder_history_self_join_lh2.ladder_change_lh2,
        datediff(cte_ladder_history_self_join_lh2.date_trigger_event_lh2,cte_ladder_history_self_join_lh1.date_trigger_event_lh1) as days_spent,
        @member_id:=member_id_lh2 AS member_id,
        @row_number:=(CASE
                WHEN @member_id = member_id_lh1
                THEN @row_number + 1
                ELSE 1
            END) AS rank 

    from 
        cte_ladder_history_self_join_lh1 #previous or current ladder history 
            left join cte_ladder_history_self_join_lh2 on cte_ladder_history_self_join_lh1.member_id_lh1 = cte_ladder_history_self_join_lh2.member_id_lh2
                and cte_ladder_history_self_join_lh2.ladder_name_lh2 = cte_ladder_history_self_join_lh1.ladder_name_lh1
                and cte_ladder_history_self_join_lh1.ladder_value_lh1 <> cte_ladder_history_self_join_lh2.ladder_value_lh2
                and cte_ladder_history_self_join_lh1.date_trigger_event_lh1 < cte_ladder_history_self_join_lh2.date_trigger_event_lh2 # lh2 shows second begin date / end date for lh if exists
        order by date_trigger_event_lh2 desc, member_id_lh1 desc; 

其中 returns 以下内容:

我不确定为什么排名不正确。我预计会有大约 1 - 20 的排名(基于符合 ladder_name = 此人的宣传标准的行数),但我得到了一些截然不同的数字。

想法?

修复了排名代码:

CREATE TEMPORARY TABLE cte_leenk_ladder_history_rank
    SELECT * ,
    @row_number:=(CASE
    WHEN @member_id = member_id
    THEN @row_number + 1
    ELSE 1
    END) AS rank,
    @member_id := member_id

    FROM 
    cte_leenk_ladder_history_order
    where ladder_change = 1
    order by salesforce_id desc, date_trigger_event desc;