2014-05-13 2 views
-1

세 가지 기록은 자신의 기록, 이전 순위 기록과 순위를 기록 후를 즉 얻는 방법 나는 아래 바이올린에 SP를했다 :MySQL의에서 agentID 및 순위에 따라 세 가지 기록을 얻는 방법

DELIMITER $$ 

CREATE DEFINER=`ntc`@`%` PROCEDURE `stckrank`() 
BEGIN 
SELECT AgentID, 
    current_day_amount, 
    month_amount, 
    year_amount, 
    @Position:[email protected] + 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 

출력 :

내가 에이전트 ID 2를 선택하면
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 

는 지금은 0

선택 에이전트 ID -2 N을 표시해야합니다 기록 이상 그렇게 널 (null) 나에 대한 어떤 기록보다 얻을 필요 EED 표시하거나 자신의 순위 기록을 얻을 기록

agentiid dayamount monthamount yearamount rank 
    2  3000  4000   7000 1 
    1  2000  3000   5000 2 
+1

당신의 바이올린은 엉망입니다. – Strawberry

답변

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 원하는 결과를 제공합니다.

이 조인을 사용하면 원본 테이블의 각 행이 항상 (항상) 자체와 이전 및 다음 순위가있는 행 (관련된 경우)에 연결됩니다.

+0

내가 내 피들을 확인 했어. http://www.sqlfiddle.com/#!2/549232/2 여기에서 나는 – user123

+0

을 얻고 싶다. @sandeep 내가 제안한 것에 무엇이 잘못 되었는가? –

+0

괜찮아요 먼저 테이블 agentid, amountreceived, datetime 여기 amountrceived 내가 threecolumns 합계 (dayamount), 합계 (monthamount), 합계 (yearamount)로 나누어 어디 agentid = agentid 저장 프로 시저를 사용하여 그래서 내가 어떻게 묻는 오전 순위를 할당 do – user123

관련 문제