How do I limit the count to 1?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Brian Connelly
    New Member
    • Jan 2011
    • 103

    How do I limit the count to 1?

    I want to loop through a table and count the ids where they are equal to a tables ids, however if the Id count is equal to 1, I would like to put that id into a table. I.e. I am trying to get the ids from a table where the id inly exists in one row. If the id exists in two or more rows, then it is excluded from my results. Can you please share insight or help me with this?

    Code:
    CREATE #TEMP
    (
    ID VARCHAR(300)
    )
    DECLARE IDNUM INT
    SET IDNUM = SELECT MIN(ID) FROM TABLE WHERE ID > 0)
    WHILE IDNUM > 0
    BEGIN
    INSERT INTO # TEMP
    SELECT ID FROM (SELECT COUNT (ID) FROM TABLE WHERE ID = IDNUM
    END
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    Code:
    INSERT INTO #tempTable
    SELECT someID
    FROM someTable
    GROUP BY someID
    HAVING COUNT(*) = 1

    Comment

    • Brian Connelly
      New Member
      • Jan 2011
      • 103

      #3
      Thank you. I forgot about Having. This was a great help.

      Comment

      Working...