2

What I want here is to retrieve pid's that have these criteria: pid count is atleast 3 and sid should atleast contain two numbers that are in sequence. For example sid should 1 & 2, 2 & 3, 3 & 4, and so on.

Table sem_attendance
attendance_id   sid    pid
            1     1      3
            6     1     12 
            8     2     12 
            9     4     12 
           10     1     23 
           11     3     23 
           12     1     29 
           13     3     27  
           14     2     24 
           15     3     21 
           16     2     21 
           17     1     27 
           18     2     27
           19     5     23

My query:

SELECT attendance_id, sid, sem_attendance.pid
FROM sem_attendance
INNER JOIN (
    SELECT pid
    FROM sem_attendance
    GROUP BY pid HAVING COUNT( pid ) =3)
temp ON sem_attendance.pid = temp.pid
ORDER BY temp.pid, sem_attendance.sid


attendance_id   sid    pid  
            6     1     12
            8     2     12
            9     4     12
           10     1     23
           11     3     23
           19     5     23
           17     1     27
           18     2     27
           13     3     27

Desired output should only be pid's 12 and 27 because the sid's 1, 3 and 5 are not in sequence. Is it possible to do this on mysql? If not, how about on php coding? Help me please.

Kevin Kopf
  • 13,327
  • 14
  • 49
  • 66
fmpsagara
  • 485
  • 5
  • 17

2 Answers2

2

You can split the two conditions into two separate subqueries and just pick rows with the pids that exist in both sets;

SELECT * FROM sem_attendance
WHERE pid IN (                           -- at least 3 in the group
  SELECT pid FROM sem_attendance
  GROUP BY pid HAVING COUNT(1) >= 3
)
AND pid IN (                             -- at least 2 consecutive
  SELECT a.pid FROM sem_attendance a JOIN sem_attendance b
    ON a.pid = b.pid AND a.sid = b.sid + 1
)

An IDEone sample to test with.

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
2

You can use the following query:

SELECT attendance_id, sid, pid 
FROM (
  SELECT attendance_id, sid, pid, 
         (SELECT sid
          FROM sem_attendance AS t2
          WHERE t1.pid = t2.pid AND t1.attendance_id < t2.attendance_id
          ORDER BY attendance_id LIMIT 1) AS next_sid
  FROM sem_attendance AS t1
  WHERE pid IN (SELECT pid
               FROM sem_attendance
               GROUP BY pid
               HAVING COUNT(*) >= 3)) AS t
WHERE sid = next_sid - 1       

I've made the assumption that field attendance_id defines order in your table. Consecutive table records are deduced based on this assumption.

Giorgos Betsos
  • 71,379
  • 9
  • 63
  • 98