1

Tricky for me to define the problem, maybe you understand it through my dummy data.

I have this data:

PK, TaskPK
1, 1    
2, 1     
3, 2    
4, 2    
5, 5    
6, 1 
7, 1     
8, 2 
9, 2   
10, 5    
11, 5

Now I have to count TaskPK so, I make this query

Select PK, TaskPK, Count(*)
From tbl
Group by TaskPK

Iit brought this result

TaskPK, Count(*)
1, 4
2, 4
5, 3

But I want slight different result Like this

TaskPK, Count(*)
1, 2
2, 2
5, 1
1, 2
2, 2
5, 2

The above result based on consecutive data occurrence, as TaskPK start with 1 (it group together), then it change it 2 (it group together), then 5 (it group together) taskPK. But as TaskPK again shift to 1, then it should group seperatly not link with previous occurrence of 1, this task seperately count, is this possible?

Strawberry
  • 33,750
  • 13
  • 40
  • 57
Muhammad Faizan Khan
  • 10,013
  • 18
  • 97
  • 186

1 Answers1

0

For Mysql - User variables to keep track of contiguous segments.Then group by this contiguous segments which are kept track by an incrementing counter,

SELECT MAX(TaskPK),COUNT(*)
FROM(SELECT PK,TaskPK,CASE WHEN  TaskPK=@TaskPK THEN @rn ELSE @rn:=@rn+1 END as g,
@TaskPK := TaskPK as task
FROM Test,(SELECT @rn:=0,@TaskPK:='')x
ORDER BY pk)z
GROUP BY g
ORDER BY pk;

See it working

Mihai
  • 26,325
  • 7
  • 66
  • 81
  • Hello, I tried running the code but got this error: `Error Code: 1055. Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 'z.PK' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by` – NothingBox Oct 14 '20 at 04:02