SQL: how to select a single id (“row”) that meets multiple criteria from a single column

后端 未结 9 2372
刺人心
刺人心 2020-11-30 05:38

I have a very narrow table: user_id, ancestry.

The user_id column is self explanatory.

The ancestry column contains the country from where the user\'s ancest

9条回答
  •  我在风中等你
    2020-11-30 06:30

    I was having a similar issue like yours, except that I wanted a specific subset of 'ancestry'. Hong Ning's query was a good start, except it will return combined records containing duplicates and/or extra ancestries (e.g. it would also return someone with ancestries ('England', 'France', 'Germany', 'Netherlands') and ('England', 'France', 'England'). Supposing you'd want just the three and only the three, you'd need the following query:

    SELECT Src.user_id
    FROM yourtable Src
    WHERE ancestry in ('England', 'France', 'Germany')
        AND EXISTS (
            SELECT user_id
            FROM dbo.yourtable
            WHERE user_id = Src.user_id
            GROUP BY user_id
            HAVING COUNT(DISTINCT ancestry) = 3
            )
    GROUP BY user_id
    HAVING COUNT(DISTINCT ancestry) = 3
    

提交回复
热议问题