sql 排名行结果
sql rank row results
我正在尝试添加一个新列,按日期显示行结果的排名(或顺序)。
我写了:
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 行有一个错误,我不确定如何修复它。对于第一个结果,我想要 return 1。对于第二个结果,我想要 return @row_number + 1。第三个结果,@row_number+2(等等).
我该如何实现?
我不明白条件 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(与所有其他数据库一样)不保证表达式求值的顺序。
- 在 MySQL 的较新版本中,我认为
ORDER BY
需要进入子查询,在外部查询中使用变量表达式。
我正在尝试添加一个新列,按日期显示行结果的排名(或顺序)。
我写了:
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 行有一个错误,我不确定如何修复它。对于第一个结果,我想要 return 1。对于第二个结果,我想要 return @row_number + 1。第三个结果,@row_number+2(等等).
我该如何实现?
我不明白条件 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(与所有其他数据库一样)不保证表达式求值的顺序。 - 在 MySQL 的较新版本中,我认为
ORDER BY
需要进入子查询,在外部查询中使用变量表达式。