Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

taking count from pair values in table

count_temp table

take the above as an output of a sample table, I need an sql query which results "2" as the count from the table.

i've tried intially while sentby column upto 4, and was okay; but more rows shows incorrect o/p. my older code is given

SELECT COUNT(*)/2
     FROM 
     (SELECT sentby,sentto
     FROM
          (SELECT DISTINCT sentby, sentto FROM count_temp)
     WHERE sentto IN
          (SELECT DISTINCT sentby FROM count_temp )
      AND sentby IN
          (SELECT DISTINCT sentto FROM count_temp )
     ) ;

Thanks in advance:) and appreciated.

like image 476
ajmalmhd04 Avatar asked Nov 04 '22 06:11

ajmalmhd04


2 Answers

Your query:

with cte as (
select distinct m1.sentby , m1.sentto
from m m1 
inner join m m2
   on m1.sentby = m2.sentto and
      m2.sentby = m1.sentto 
)
select count(*)/2 from cte;

test it at sqlfiddle

Also, simplifying:

select count( distinct m1.sentby ) / 2
from m m1 
inner join m m2
   on m1.sentby = m2.sentto and
      m2.sentby = m1.sentto 
like image 94
dani herrera Avatar answered Nov 15 '22 06:11

dani herrera


Try this one:

    SELECT count(*)/2
    FROM
      (SELECT sentby,
              sentto,
              max(rownum) AS rn
       FROM count_temp
       GROUP BY sentby,
                sentto) a,
      (SELECT sentby,
              sentto,
              max(rownum) AS rn
       FROM count_temp
       GROUP BY sentby,
                sentto) b
    WHERE a.rn != b.rn
      AND a.sentby = b.sentto
      AND a.sentto = b.sentby;  
like image 34
MikA Avatar answered Nov 15 '22 05:11

MikA