Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query to get only those rows with only 1 value in another column

Tags:

sql

I have a table like this:

Sample Table

I need a query to return only those ProjectID's that have only State=21. i.e I want only ProjectID 2 & 5.

I do not want those records with ProjectID 1, 3, 4 & 6, because in those case, the state is also equal to other numbers

like image 308
Devdatta Tengshe Avatar asked Apr 08 '26 07:04

Devdatta Tengshe


2 Answers

Reasoning goes like

  • In a subselect, select all ProjectID's that have a state = 21
  • In the outer select, retain only those ProjectID's that only have a state = 21 using a HAVING clause

SQL Statement

SELECT  ProjectID
FROM    table t1
        INNER JOIN (
          SELECT  ProjectID
          FROM    table
          WHERE   state = 21
        ) t2 ON t2.ProjectID = t1.ProjectID
GROUP BY
        ProjectID
HAVING  COUNT(*) = 1        
like image 196
Lieven Keersmaekers Avatar answered Apr 09 '26 21:04

Lieven Keersmaekers


Select all the projects with a single state value, which ('the value') is, by the way, equal to the specified one:

SELECT   ProjectID
FROM     atable
GROUP BY ProjectID
HAVING   COUNT(*) = 1
   AND   MAX(State) = @State

You can also use MIN, SUM, or AVG to check the value of State with the same effect (because it should be the only value).

like image 27
Andriy M Avatar answered Apr 09 '26 19:04

Andriy M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!