1

我有以下 sql,它首先根据“报告”列选择最经常出现的行

 $datan = mysql_query("
   SELECT *, COUNT(reported) AS ct
   FROM profile_reports
   WHERE open = '1'
   GROUP BY reported
   ORDER BY ct DESC
   LIMIT 1
 ") or die(mysql_error());

我希望我的 sql 还检查哪个“报告者”(每个都是与用户关联的数字)具有最佳百分比的有用报告,这是通过以下方式确定的:

((raction > 0 AND raction < 99 AND open = '0' AND reporter = 'reporter') / (reporter = 'reporter' AND open = '0')) * 100

...并首先显示百分比最高的行。这有点棘手,因为没有设置初始记者。

这是一个示例表:

+----+----------+----------+-------+----------+
| id | reporter | reported | open  |  raction |
+----+----------+----------+-------+----------+
|  1 |       24 |    26    |  0    |  3       |
|  2 |       24 |    23    |  0    |  0       |
|  3 |       24 |    29    |  1    |          |
|  4 |       12 |    29    |  0    |  4       |
|  5 |       12 |    29    |  1    |          |
|  6 |       24 |    21    |  1    |  0       |
+----+----------+----------+-------+----------+

我希望它看到关于用户 29(列:报告)的更多报告,然后检查哪个报告用户(列:报告者)具有最佳百分比(基于上面的代码行),在这种情况下是用户 12,并且显示他们的报告

4

1 回答 1

3

它实际上非常容易,只需将您的条件总和除以即可。为了正确获得“报告”,您需要使用内联视图来查找最高报告。

SELECT pr.*, 
       ( Sum(pr.raction > 0 
             AND pr.raction < 99 
             AND pr.open = '0' 
             AND pr.reported = t.reported) / Sum(pr.reported = t.reported 
                                                 AND pr.open = '0') ) * 100 AS 
       usefull 
FROM   profile_reports pr, 
       (SELECT reported 
        FROM   profile_reports 
        WHERE  open = '1' 
        GROUP  BY reported 
        ORDER  BY Count(reported) DESC 
        LIMIT  1) t 
GROUP  BY reporter 
ORDER  BY usefull DESC 
LIMIT  1 

演示

输出

| ID | REPORTER | REPORTED | OPEN | RACTION | USEFULL |
-------------------------------------------------------
|  4 |       12 |       29 |    0 |       4 |     100 |

我还没有为你做所有事情。如果除数为零,您将不得不决定该怎么做

请注意除了 MySQL 之外的所有内容,您需要使用 CASE

   SUM ( CASE WHEN raction > 0 AND .... THEN 1 ELSE 0 END) / ....
于 2012-07-12T22:26:38.763 回答