如何获得三个记录,即他的记录,以前的等级记录和等级记录 我在下面的小提琴里有SP:
DELIMITER $$
CREATE DEFINER=`ntc`@`%` PROCEDURE `stckrank`()
BEGIN
SELECT AgentID,
current_day_amount,
month_amount,
year_amount,
@Position:=@Position + 1 AS `Rank`
FROM
(
SELECT just_agent.AgentID,
total_current_date.Totoalamountperday AS current_day_amount,
total_current_month.Totoalamountpermonth AS month_amount,
total_year.Totoalamountperyear AS year_amount
FROM
(
SELECT DISTINCT AgentID
FROM collection
) just_agent
LEFT OUTER JOIN
(
select AgentID, SUM(AmountRecevied) as Totoalamountperday
from collection
where day(Date_Time) = day(CURRENT_DATE())
group by AgentID
) total_current_date
ON just_agent.AgentID = total_current_date.AgentID
LEFT OUTER JOIN
(
select AgentID, sum(AmountRecevied) as Totoalamountpermonth
from collection
where date_time between DATE_FORMAT(NOW(), '%Y-%m-01') and LAST_DAY(now() - interval 0 month)
group by AgentID
) total_current_month
ON just_agent.AgentID = total_current_month.AgentID
LEFT OUTER JOIN
(
select AgentID, sum(AmountRecevied) as Totoalamountperyear
from collection
where year(Date_Time) = YEAR(CURRENT_DATE())
group by AgentID
) total_year
ON just_agent.AgentID = total_year.AgentID
ORDER BY total_year.Totoalamountperyear DESC
) Sub1
CROSS JOIN (SELECT @Position:=0) Sub2;
END
输出:
agentiid dayamount monthamount yearamount rank
2 3000 4000 7000 1
1 2000 3000 5000 2
3 200 300 500 3
4 100 100 200 4
现在,如果我选择代理商ID 2,我需要获得以下记录并且没有上述记录,所以null或0应该显示
选择代理商ID -2 需要展示或获得 他的排名记录和记录之后
agentiid dayamount monthamount yearamount rank
2 3000 4000 7000 1
1 2000 3000 5000 2
答案 0 :(得分:3)
您可以按等级条件将表格连接到自身:
SELECT t2.*
FROM yourTable t1
JOIN yourTable t2
ON ABS(t1.rank - t2.rank) <= 1.5 --is this what you want ?
WHERE t1.agentiid = 2
This SQL fiddle提供了理想的结果。
使用此连接,原始表中的每一行都与自身(始终)以及具有上一级和下一级(如果存在)的行相关联。