简体   繁体   中英

SQL Server - Returning Multiple Rows Based on 'IF' Criteria

with a better explanation:

I'm working in SQL server joining tables that that have multiple rows for each entity - or 'House' in my example data. I want only those 'House UIDs' that have a type of Garden, Drive and Entrance hall in the table I'm joining to. It doesn't matter if they have more than that, but there must be House_UID rows with at least Garden, Drive and Entrance hall as a 'Thing type' value for the House_UID to be returned.

In the example data this would be 1 and 3.

I've tried

Select HOUSE_UID, THING_TYPE from HOUSES

Join HOUSE_THINGS on HOUSES.HOUSE_THING = HOUSE_THINGS.THING

WHERE HOUSE_UID in (select HOUSE_UID from houses 
                    Join HOUSE_THINGS on HOUSES.HOUSE_THING = HOUSE_THINGS.THING
                   where house_thing = x)
   and HOUSE_UID in (select HOUSE_UID from houses 
                    Join HOUSE_THINGS on HOUSES.HOUSE_THING = HOUSE_THINGS.THING
                   where house_thing = y)

   and HOUSE_UID in (select HOUSE_UID from houses 
                    Join HOUSE_THINGS on HOUSES.HOUSE_THING = HOUSE_THINGS.THING
                   where house_thing = z)

but this doesn't seem to work - I'm getting results that don't have rows for everything I'm interested in. Any new ideas welcome!

Thanks

示例数据

use aggregation

select houseid from table_name
where house in ('Garden', 'Drive','Entrance hall')
group by houseid
having count(distinct house)>=3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM