Search code examples
sqlsql-servercountrelational-divisionhaving-clause

Select Common Column Values in SQL


I have a SQL table like

 docid            State
12                  MP
13                  MP
14                  MP
13                  CG
14                  CG
12                  MH
13                  MH
16                  DL

I want a SQL query where I can get a result with only common "docid" for all the three states "MP","CG","MH"

Like

Docid   
13

Note: States are entered from user id in Where states = ""


Solution

  • I just used sqlite3 to reproduce your scenario using the following SQL commands:

    CREATE TABLE tablename (
        docid INT,
        State VARCHAR(2)
    );
    INSERT INTO tablename VALUES (12,'MP');
    INSERT INTO tablename VALUES (13,'MP');
    INSERT INTO tablename VALUES (14,'MP');
    INSERT INTO tablename VALUES (13,'CG');
    INSERT INTO tablename VALUES (14,'CG');
    INSERT INTO tablename VALUES (12,'MH');
    INSERT INTO tablename VALUES (13,'MH');
    INSERT INTO tablename VALUES (16,'DL');
    

    Then I was able to query what you are looking for using:

    SELECT mp.docid AS Docid
    FROM tablename AS mp
    JOIN tablename AS cg ON mp.docid = cg.docid
    JOIN tablename AS mh ON cg.docid = mh.docid
    WHERE mp.State='MP' AND cg.State='CG' AND mh.State='MH';
    

    which returned 13