5

count_temp 表

将上述内容作为示例表的输出,我需要一个 sql 查询,其结果为“2”作为表中的计数。

我已经尝试过在第 4 列中发送,并且还可以;但更多行显示不正确的 o/p。给出了我的旧代码

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 )
     ) ;

在此先感谢:) 并表示赞赏。

4

2 回答 2

1

您的查询:

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;

在 sqlfiddle 测试它

此外,简化:

select count( distinct m1.sentby ) / 2
from m m1 
inner join m m2
   on m1.sentby = m2.sentto and
      m2.sentby = m1.sentto 
于 2013-01-22T08:17:54.983 回答
1

试试这个:

    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;  
于 2013-01-22T08:36:19.147 回答