我正在尝试添加一个新列,以按日期显示行结果的排名(或序列)。
我写了:
SELECT
@row_number:=(CASE
WHEN @member_id = lh.member_id and lc.ladder_advocacy is not null
THEN @row_number + 1
when @member_id = lh.member_id and lc.ladder_advocacy is null then "null"
ELSE 1 /* there is an error here - i need it to return a 1 if not null, then 2 for the 2nd instance, etc */
END) AS rank_advocacy,
@member_id:=lh.member_id AS member_id,
lh.ladder_change,
lc.name,
lc.ladder_advocacy,
lc.ladder_elected,
lc.ladder_policy,
lc.ladder_engagement,
lc.ladder_newventure,
lc.ladder_collective,
lc.is_trigger
FROM
leenk_ladder_history AS lh
LEFT JOIN
leeds_so.leenk_ladder_config AS lc ON lh.ladder_config_id = lc.id
WHERE
ladder_change = 1 AND trigger_active = 1
ORDER BY member_id, trigger_event_date DESC;
第4行有错误,我不确定如何解决。对于第一个结果,我想返回1.对于第二个结果,我想返回@row_number +1。第三个结果,@ row_number + 2(等等)。
我该如何实现?
答案 0 :(得分:0)
我不知道条件lc.ladder_advocacy is not null
是如何使用的。但是,基本结构是:
SELECT (@row_number = IF(@member_id = lh.member_id, @row_number + 1
IF(@member_id := lh.member_id, 1, 1)
)
) as rank_advocacy,
lh.ladder_change,
. . .
一些非常重要的观点:
@member_id
和@row_number
。 MySQL(与所有其他数据库一样)不保证表达式的求值顺序。ORDER BY
需要进入子查询,并且变量表达式位于外部查询中。