Problem with COUNT() - Can you help!

Discussion in 'MySQL' started by adzeds, Feb 2, 2010.

  1. #1
    Ok.
    Here is the query that I am running:

    $Query = "SELECT DISTINCT session, COUNT(session) As bounces from analytics GROUP BY session";
    PHP:
    What I want to do is only return the rows where the bounces column is equal to 1.

    How would I do this?
     
    adzeds, Feb 2, 2010 IP
  2. plog

    plog Peon

    Messages:
    298
    Likes Received:
    11
    Best Answers:
    1
    Trophy Points:
    0
    #2
    First, don't use 'DISTINCT' when you use 'GROUP BY' . Second, to limit your query by any criteria use the 'WHERE' clause on the data not its alias (the name you gave it, i.e. 'bounces'):

    $Query = "SELECT session, COUNT(session) AS bounces FROM analytics WHERE COUNT(session)=1 GROUP BY session";
    PHP:
     
    plog, Feb 2, 2010 IP
  3. adzeds

    adzeds Well-Known Member

    Messages:
    1,209
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    100
    #3
    Thanks for the response.

    I tried implementing your code but got the following error:

    Invalid use of group function
     
    adzeds, Feb 2, 2010 IP
  4. adzeds

    adzeds Well-Known Member

    Messages:
    1,209
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    100
    #4
    I have fixed this issue.
    I had to use the HAVING statement after the GROUP BY instead of the WHERE.

    Here is my functioning code:

    $Query = "SELECT session, COUNT(session) AS bounces FROM analytics GROUP BY session HAVING COUNT(session)=1";
    PHP:
     
    adzeds, Feb 2, 2010 IP
  5. plog

    plog Peon

    Messages:
    298
    Likes Received:
    11
    Best Answers:
    1
    Trophy Points:
    0
    #5
    Its not a 'WHERE' clause its a 'HAVING' clause because you are grouping. I apologize. Try this code:
    SELECT session, Count(session) AS bounces FROM analytics GROUP BY session HAVING (Count(session)=1);
    PHP:
     
    plog, Feb 2, 2010 IP