2016-09-29 120 views
0

有人可以解釋如何做下列事情嗎? 我有一張桌子的人和房子。

人:當其中一行滿足條件時不要選擇行

| 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 | 

我有以下情況: 我需要選擇的人誰擁有了一套住宅,類型爲「大」,而不是選擇這個人,如果他有類型爲「小」的房屋,如果他有兩個類型爲「大」和「未定義」的房屋,則選擇人,但不選擇類型爲「未定義」的房屋的房屋編號。

所以結果應該是(僅這一個排)

| Person id | House id | 
| 2   | 4  | 
+0

哪些DBMS您使用的工作嗎? –

+0

你正在離開很多組合,例如,如果他有大/大/大/未定義,......會發生什麼?也許你可以用另一種方式解釋理想的結果? –

+0

人1和人2都有大和未定義爲什麼人1不在列表中? – Stivan

回答

2

把它一步一步

,我需要選擇的人誰擁有了一套住宅,類型爲「大」

SELECT DISTINCT PersonID, HouseID 
FROM HOUSES 
WHERE HouseType = 'Big' 

而不是選擇這個人,如果他有房e爲類型爲 「小」,

SELECT DISTINCT PersonID, HouseID 
FROM HOUSES 
WHERE HouseType = 'Big' 
    AND PersonID NOT IN (SELECT PersonID FROM HOUSES WHERE HouseType = 'small') 

選擇的人,如果他有2間房子,類型爲 「大」 和 「未定義」

(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' 
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操作中使用的子查詢返回涉及到兩個「大」和「不確定」戶型PersonId值,而不是相關到「小」的。

Demo here

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' 
相關問題