如何从单个表中找到共同的价值?

时间:2016-08-04 22:17:45

标签: mysql sql sql-server

From this table

---------------------------
|  id        | country     |
---------------------------
|  1         | India       |
---------------------------
|  2         | India       |
---------------------------
|  2         | India       |
---------------------------
|  3         | India       |
---------------------------
|  1         | U.S.        |
---------------------------
|  1         | U.S.        |
---------------------------
|  2         | U.K.        |
---------------------------
|  2         | U.K.        |
---------------------------
|  2         | U.K.        |
---------------------------

i need to achieve this result

--------------
|  id        |
--------------
|  1         |
--------------
|  2         |
--------------

Scenario: I need to get the common id for country 'India' as well as non 'India'

Please, help me to achieve this.

2 个答案:

答案 0 :(得分:0)

尝试使用IN

SELECT  id
FROM    mytable
WHERE   country = 'India'
        AND id IN ( SELECT  id
                    FROM    mytable
                    WHERE   country <> 'India' )

答案 1 :(得分:0)

这是一种方法:

select id
from
    (
    select id
    from CountryIDs 
    group by id, case when country = 'India' then 1 else 0 end
    ) ids
group by id
having COUNT(*)=2