-1

So I have a table like this:

|---group---|---property---|---value---|
|     a     |   prop1      |    yes    |
|     a     |   prop2      |    yes    |
|     a     |   prop3      |    no     |
|     b     |   prop1      |    yes    |
|     b     |   prop2      |    no     |
|     b     |   prop3      |    no     |
|     c     |   prop1      |    no     |
|     c     |   prop2      |    no     |
|     c     |   prop3      |    no     |

I need to filter out only those groups that have yes near prop1. I could use having statement, but this would take any yes value. The problem is that I do not have my properties as column names but as rows in a column instead. Soooo... is it even possible to do this?

There should be only groups a and b in my resulting table...

Serg
  • 22,285
  • 5
  • 21
  • 48
milka1117
  • 521
  • 4
  • 8
  • 17

4 Answers4

3

You can use sub query to pick first the list of groups that has value Property = 'prop1' and Value = 'Yes'. Then select all records for those list of Groups as below-

SELECT * 
FROM your_table
WHERE Group IN(
    SELECT DISTINCT `Group`
    FROM your_table
    WHERE `Property` = 'prop1'
    AND `Value` = 'Yes'
)

You can add several different properties as-

....
WHERE 
(
    `Property` = 'prop1'
    AND `Value` = 'Yes'
)
AND -- You can also use OR here if you need rows if any of the condition is true
(
    `Property` = 'prop3'
    AND `Value` = 'No'
)
mkRabbani
  • 16,295
  • 2
  • 15
  • 24
1

Single propety is straightforward

select distinct group 
from myTable
where property = 'prop1' and  value ='yes';
Serg
  • 22,285
  • 5
  • 21
  • 48
1

You can use EXISTS:

select t.* from tablename t
where exists (
  select 1 from tablename
  where `group` = t.`group`
  and (
    (property = 'prop1' and `value` = 'yes')
    or
    (property = 'prop2' and `value` = 'no') 
  )
)

You can combine conditions in the subquery.

forpas
  • 160,666
  • 10
  • 38
  • 76
0

Just FYI, you can also write this (although it may have more limited ability to utilise indexes...

SELECT * FROM my_table WHERE(x,y) IN((1,'yes'),(2,'no'),(3,'maybe'));
Strawberry
  • 33,750
  • 13
  • 40
  • 57