sql - MySQL: Count of records with consecutive months -
I searched for it, but all the same questions and answers are not enough to just work.
I have a table with the following fields: person, thing, purity, a new record is recorded when a person buys every new thing.
I have to count the months in my life, who gave a person "cheese" (cheese 01 or cheese 02, it is not a mater). If there is a break in fourteen consecutive times, then counting should begin.
Attached to the data, I want to end it:
| Person Days of Cones | | Person_01 | 3 | | Person_02 | 3 | | Person_02 | 2 | I know that I can get a different list of people, (year old to remove) - what I have done in this - but I'm not sure how to count then Continuous record and start at break (like my data, where the person breaks between 0/22 March and May.)
Here is the data:
Table record (Person varchar (32) not tap, talk varchar (32) no null, vintage date time zero); Enter the record (person, object, purity) values ('person_01', 'thing01', '2014-01-02'), ('person_01', 'thing02', '2014-01-02'), ('person_01 ',' Cheese 02 ',' 2014-02-27 '), (' person_01 ',' cheese 02 ',' 2014-03-27 '), (' person_02 ',' cheese 02 ',' 2014-01-28 ') , ('Person_02', 'thing01', '2014-02-28'), ('person_02', 'thing02', '2014-03-28'), ('person_02', 'thing02', '2014-05 -29 '), (' person_02 ',' thing02 ',' 2014-06-29 ');
You can use it in MySQL variable (or very complex correlated subqueries) . In other databases, you will use window / analytical functions.
The reasoning is this:
- Get a line per month and get the person with the purchase.
- Use variables to specify a "group" value for each group of consecutive months.
- AuP from the person and "group" value
Here is a query tested on your SQL Bedle:
select the person, select from nummonths as count (*) ( Grp as a person, ym, @ym, @person, if (@person = person and @ym = Ym - 1, @grp, @grp: = @grp + 1), @person: person = @ym: = ym (Select different person, year (purdate) * 12+ months (purdate) Record from ym R) R cross join (select @ man: = '', @ yam: = 0, @grip: = 0 1) Constant order, 2) PAM group by person, GRP;
Comments
Post a Comment