有人可以解释如何做以下事情吗?
我有一张桌子人和房子。
人:
| Person id | Person Name |
| 1 | One |
| 2 | Two |
房屋:
| House id | Person Id | House type |
| 1 | 1 | Small |
| 2 | 1 | Big |
| 3 | 1 | Undefined |
| 4 | 2 | Big |
| 5 | 2 | Undefined |
我有以下情况: 我需要选择拥有“Big”类型房子的人,如果他有“小”类型的房子,则不选择此人,如果他有2个类型为“big”和“Undefined”的房子,请选择此人,但不选择房屋“未定义”类型的房子的ID。
所以结果应该是(只有这一行)
| Person id | House id |
| 2 | 4 |
答案 0 :(得分:2)
一步一步地采取行动
我需要选择拥有类型" Big"
的房子的人
SELECT DISTINCT PersonID, HouseID
FROM HOUSES
WHERE HouseType = 'Big'
如果他的房子类型为"小",
,请不要选择此人
SELECT DISTINCT PersonID, HouseID
FROM HOUSES
WHERE HouseType = 'Big'
AND PersonID NOT IN (SELECT PersonID FROM HOUSES WHERE HouseType = 'small')
如果他有2个类型为" big"和"未定义"
(SELECT PersonID FROM HOUSES WHERE HouseType = 'big')
UNION
(SELECT PersonID FROM HOUSES WHERE HouseType = 'undefined')
但不选择类型"未定义"的房子的房屋ID。
SELECT DISTINCT PersonID, HouseID
FROM HOUSES
WHERE PersonID IN (
(SELECT PersonID FROM HOUSES WHERE HouseType = 'big')
UNION
(SELECT PersonID FROM HOUSES WHERE HouseType = 'undefined')
)
AND HouseType != 'undefined'
答案 1 :(得分:0)
您可以使用以下查询:
SELECT PersonId, HouseId
FROM Houses
WHERE HouseType = 'Big' AND
PersonId IN (SELECT PersonId
FROM Houses
GROUP BY PersonId
HAVING COUNT(CASE WHEN HouseType = 'Big' THEN 1 END) >= 1 AND
COUNT(CASE WHEN HouseType = 'Small' THEN 1 END) = 0 AND
COUNT(CASE WHEN HouseType = 'Undefined' THEN 1 END) >= 1)
IN
运算符使用的子查询返回与“' Big'”相关的PersonId
值。和'未定义'房屋类型和不与' Small'的。
答案 2 :(得分:0)
这应该有效
select case2.Person_ID, case2.House_ID
from (
( -- Removes persons with Big and Small houses
select Person_ID, count(*) as Cnt from Houses
where House_Type in ('Big', 'Small')
group by Person_ID
having count(*) = 1
) case1
inner join
(
select Person_ID, House_ID, House_Type from Houses
where House_Type in ('Big', 'Undefined')
) case2 on case1.Person_ID = case2.Person_ID
)
where House_Type <> 'Undefined'