Domanda

I am in school and trying to figure out this question asked by the instructor. I have not asked the instructor because he usually gets back to me 2 weeks down the road.

Here is what the questions is asking:

Using the weblog table in your database create a query that will use the WHEN statement to:

categorize the records by the origcmd field meeting the following conditions Your categories should be as follows:

•Category 1 = origcmd starts with GET

•Category 2 = origcmd starts with POST

•Category 3 = origcmd starts with HEAD

•Category 4 = All of the left over records

•Count the records in each group •Average the hours part of the origdate field without modifying the field.

I have tried the following without the Average because I cannot get it to pull correctly with the following:

Select CASE 
WHEN origcmd LIKE "GET%" THEN "Category 1"
WHEN origcmd LIKE"POST%" THEN "Category 2"
WHEN origcmd LIKE "HEAD%" THEN "Category 3"
Else "Category 4 All of left over records" END as "Original CMD",
Count(*) AS Total
FROM WebLog 

When using this it only pulls the first WHEN line and ignores all the rest except the count. I am new at this and am having a difficult time trying to understand MySQL. I think I might need to use a SubString cmd but was hoping for a little direction here that might help.

Regards,

È stato utile?

Soluzione

UPDATED:

SELECT category,
       CASE category WHEN 1 THEN 'GET' WHEN 2 THEN 'POST' WHEN 3 THEN 'HEAD' ELSE 'OTHER' END command,
       COUNT(*) rec_count, 
       ROUND(AVG(SUBSTRING(origdate, 14, 2))) avg_hour
FROM
(SELECT w.*, 
        CASE WHEN LEFT(origcmd, 3) = 'GET'  THEN 1
             WHEN LEFT(origcmd, 4) = 'POST' THEN 2
             WHEN LEFT(origcmd, 4) = 'HEAD' THEN 3
        ELSE 4 END category
   FROM WebLog w) q
 GROUP BY category

Output:

| CATEGORY | COMMAND | REC_COUNT | AVG_HOUR |
---------------------------------------------
|        1 |     GET |         4 |       10 |
|        2 |    POST |         3 |       14 |
|        3 |    HEAD |         1 |       17 |
|        4 |   OTHER |         2 |        6 |

SQLFiddle

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top