MS-SQL question about GROUP BY

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • denitram
    New Member
    • Feb 2007
    • 2

    MS-SQL question about GROUP BY

    Hi,

    I have a table that has email, q1,q2 etc. I would like to select each email and the result should have each email listed once with the values of q1,q2,q3 & q4.

    For example:
    email-------------q1---q2
    a@domain-----a
    b@domain-----a
    a@domain-------------b
    b@domain-------------a

    the result should be:
    email------------q1---q2
    a@domain-----a----b
    b@domain-----a----a

    with the query:
    Code:
    SELECT email, q1, q2, q3, q4 FROM my_table
    GROUP BY email
    ORDER BY email
    I get the following error:
    "Column 'mytable.q1' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"

    and this query gives every back without grouping:
    Code:
    SELECT email, q1, q2, q3, q4 FROM my_table
    GROUP BY email,q1,q2,q3,q4
    ORDER BY email
    How can I resolve my problem?

    Thanx in advance.

    Denitram
  • almaz
    Recognized Expert New Member
    • Dec 2006
    • 168

    #2
    Solution depends on what do you expect to get when there are several records for particular email with different values for q1, i.e.
    Code:
    email     q1  q2
    a@domain  a
    a@domain  b
    Following solution gets a maximum from "a" and "b" for my example.
    Code:
    SELECT email, max(q1), max(q2), max(q3), max(q4)
    FROM my_table
    GROUP BY email
    ORDER BY email

    Comment

    • denitram
      New Member
      • Feb 2007
      • 2

      #3
      Originally posted by almaz
      Solution depends on what do you expect to get when there are several records for particular email with different values for q1, i.e.
      Code:
      email     q1  q2
      a@domain  a
      a@domain  b
      Following solution gets a maximum from "a" and "b" for my example.
      Code:
      SELECT email, max(q1), max(q2), max(q3), max(q4)
      FROM my_table
      GROUP BY email
      ORDER BY email
      Thank you a lot, it's working

      Comment

      Working...