0

问题是这样的:创建一个查询,该查询将对 IP 地址进行分组,并显示每个 IP 地址的请求数总和,其返回代码 ( retcode) 大于 300 按retcode字段降序排列此查询。

我想出的是这个(经过几个小时的努力)

SELECT ipno, retcode, IF(retcode > 300, 1, 0) AS 'return'
FROM WebLog 
GROUP BY ipno
HAVING SUM(retcode) > 300
ORDER BY retcode DESC

当然它没有回答这个问题,我只是没有解决方案。

有没有办法在 IF 或 CASE 语句中使用聚合函数,例如:

IF(retcode > 300, SUM retcode, 0)

我认为如果我知道如何在查询中正确编写它,这将起作用。

4

1 回答 1

0

Actually, the problem doesn't make sense. One can group & count on IP address, as in the following query:

SELECT   ipno, COUNT(*)
FROM     Weblog
WHERE    retcode > 300
GROUP BY ipno

However, suppose that there are two requests from a particular IP but with different return codes (say 350 and 400); the above query will show a count of two for that address, but what does it mean to sort the results by return code when (now that the results have been grouped) there is now no single such code for that one IP address?

MySQL is exceptional in that it permits you to access "hidden" columns (such as retcode in the above query) without encompassing in an aggregate function; other RDBMS would raise an error with the query you gave in your question. However, for performance reasons MySQL chooses an indeterminate value amongst those in each group for the hidden column so unless they are all the same one should not rely on the results.

Perhaps you want to group on ipno and retcode:

SELECT   ipno, retcode, COUNT(*)
FROM     Weblog
WHERE    retcode > 300
GROUP BY ipno, retcode
ORDER BY retcode DESC
于 2013-05-05T17:32:15.293 回答