简体   繁体   中英

CASE SQL statement

I am curious if any one can tell me what I am doing wrong, or point me in the right direction. If someone can give me a hand, I would be thankful.

Here is the question: Using the weblog table in your database create a query that will Group the IP addresses and display a sum of the number of requests by each IP address that had a return code (retcode) of greater than 300 order this query by the retcode field in descending order.

Here is what I have so far:

SELECT COUNT(ipno) AS Number_of_Requests, retcode
FROM WebLog
GROUP BY ipno
HAVING retcode > 300
ORDER BY retcode DESC

The question is basically "wrong". The problem is that it is asking for results at the ip level and then asking for you to order by the return code. But a given IP could have more than one return code meeting the criteria.

One valid interpretation is that it really means "group by ip and retcode":

SELECT ipno, retcode, COUNT(ipno) AS Number_of_Requests
FROM WebLog
WHERE retcode) > 300
GROUP BY ipno
ORDER BY retcode DESC;

Another valid interpretation is that it means to order by the maximum retcode for each IP:

SELECT ipno, COUNT(ipno) AS Number_of_Requests
FROM WebLog
WHERE retcode > 300
GROUP BY ipno
ORDER BY MAX(retcode) DESC;

For this query, I would include GROUP_CONCAT(DISTINCT retcode) to see a list of such codes.

To be honest, I suspect the write of the question intended for the ORDER BY to be by the number of log entries, and the phrasing just came out wrong.

You need to move the filter clause to where . Also, it doesn't make sense to sort by retcode when you are grouping by IP.

If you really want to do that, use an aggregate function on retcode (say max ):

SELECT ipno, COUNT(ipno) AS Number_of_Requests, max(retcode)
FROM WebLog
where retcode > 300
GROUP BY ipno
ORDER BY max(retcode) DESC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM