SQL query that gives distinct results that match multiple columns

前端 未结 4 1845
渐次进展
渐次进展 2020-12-03 16:06

Sorry, I couldn\'t provide a better title for my problem as I am quite new to SQL. I am looking for a SQL query string that solves the below problem.

Let\'s assume t

4条回答
  •  臣服心动
    2020-12-03 17:10

    This assumes DocumentID and Tag are the Primary Key.

    Edit: Changed HAVING clause to count DISTINCT tags. That way it doesn't matter what the primary key is.

    Test Data

    -- Populate Test Data
    CREATE TABLE #table (
      DocumentID varchar(8) NOT NULL, 
      Tag varchar(8) NOT NULL
    )
    
    INSERT INTO #table VALUES ('1','tag1')
    INSERT INTO #table VALUES ('1','tag2')
    INSERT INTO #table VALUES ('1','tag3')
    INSERT INTO #table VALUES ('2','tag2')
    INSERT INTO #table VALUES ('3','tag1')
    INSERT INTO #table VALUES ('3','tag2')
    INSERT INTO #table VALUES ('4','tag1')
    INSERT INTO #table VALUES ('5','tag3')
    
    INSERT INTO #table VALUES ('3','tag2')  -- Edit: test duplicate tags
    

    Query

    -- Return Results
    SELECT DocumentID FROM #table
    WHERE Tag IN ('tag1','tag2')
    GROUP BY DocumentID
    HAVING COUNT(DISTINCT Tag) = 2
    

    Results

    DocumentID
    ----------
    1
    3
    

提交回复
热议问题