I want to find the client's code (cCode), who bought more than 1 million units, in three consecutive months.
Here is my data:
gDate cCode buy
2014-10-22 15108164 1653410
2014-12-22 15108164 1653410
2014-10-22 16100286 1255720
2014-11-22 16100286 1739850
2014-12-22 16100286 1255720
2014-09-22 12400573 1336000
2014-10-22 12400573 1336000
2014-12-22 12400573 1336000
2014-12-22 12600125 3592800
2014-10-22 12600125 1266200
where cCode is the client's code, or ID.
Result must:
------------------------------------------------------------
cCode 2014-09-* 2014-10-* 2014-11-* 2014-12-* |
------------------------------------------------------------
15108164 - Yes - Yes |
16100286 - Yes Yes Yes | <- OK
12400573 Yes Yes - Yes |
12600125 - Yes - Yes |
------------------------------------------------------------
Answer is(cCode) : 16100286
I update function
DELIMITER $$
CREATE FUNCTION `milad`(D date,I int ,mMonth int ,minBuy int) RETURNS tinyint(1)
BEGIN
DECLARE result TINYINT Default 1 ;
DECLARE m_counter INT Default 0 ;
myloop: WHILE m_counter < mMonth DO
if((SELECT count(cCode) as a FROM milad WHERE
year(gDate) = year(DATE_ADD(D,INTERVAL m_counter month))
and month(gDate) = month(DATE_ADD(D,INTERVAL m_counter month))
and buy>minBuy
and cCode=I)=0) THEN SET result = 0;
END IF;
SET m_counter = m_counter+1;
END WHILE myloop;
IF(result=1)
THEN RETURN true;
ELSE RETURN false;
end if;
end
LIKEfor comparing date intervals? Ewww ... – ypercubeᵀᴹ Jan 17 '15 at 22:16LIKE? – Greenonline Jan 17 '15 at 22:48(gdate >= @month_start AND gdate < @next_month_start)where the month start are dates calculated like yourDATE_ADD(t1.gDate,INTERVAL 1 month)– ypercubeᵀᴹ Jan 17 '15 at 22:54