SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Wizard boxhead's Avatar
    Join Date
    Feb 2004
    Location
    UK
    Posts
    1,040
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Group and then count distinct

    I could do the following as several queries or a view and then a query but i would like to do as one query.

    I have a table with 2 columns Type and LinkID - both contain a number. Type contains 1, 2 or 3 and LinkID contains a number reference which could link to the same record:

    Type LinkID
    1 4
    1 4
    1 4
    1 6
    2 3
    2 3
    2 3
    3 4
    3 5
    3 6
    3 7

    What I want to do is count the number of distinct LinkIDs for each type, giving:

    Type Count
    1 2
    2 1
    3 4

    how do I do this?

    cheers
    monkey - the rest is history

  2. #2
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,215
    Mentioned
    58 Post(s)
    Tagged
    3 Thread(s)
    Code:
    SELECT type
         , COUNT(DISTINCT linkid) AS count
      FROM daTable
    GROUP
        BY type


    p.s. why does your table have duplicate rows in the first place -- that's the real wtf here
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"

  3. #3
    SitePoint Wizard boxhead's Avatar
    Join Date
    Feb 2004
    Location
    UK
    Posts
    1,040
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by r937 View Post
    Code:
    SELECT type
         , COUNT(DISTINCT linkid) AS count
      FROM daTable
    GROUP
        BY type


    p.s. why does your table have duplicate rows in the first place -- that's the real wtf here
    Thanks - I think I must have tried every combo but that one

    p.s. the example is a massive simplification of the problem - my tables really aren't that stupid (I hope!)
    monkey - the rest is history


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •