SQL选择带过滤器的行

时间:2015-09-09 08:35:17

标签: mysql sql

我有下表:

+----+----------+
| id | feature  |
+----+----------+
| 1  |   10     |
| 1  |   20     |
| 2  |   20     |
| 3  |   40     |
| 4  |   50     |
| 5  |   60     |
+----+----------+

并且我希望拥有同时具有10和20功能的ID。因此,不仅仅是10或20的结果,而且我希望得到结果同时包含10和20的id。

3 个答案:

答案 0 :(得分:3)

最简单的方法是GROUP BY id并使用HAVING

SELECT id
FROM table_name
WHERE feature IN (10,20)
GROUP BY id
HAVING COUNT(distinct feature) = 2

答案 1 :(得分:2)

另一种选择具有功能10和20的ID的方法可以这样做

select id
from table1
group by id
having sum(feature = 10)
and sum(feature = 20)

DEMO

答案 2 :(得分:0)

另一种方法

SELECT ID,
stuff(
(
    select ','+ convert(varchar,feature) from table where Id = t.Id for XML path('')
),1,1,'') [comma_sep_feature]
FROM [table] t 
group by id

您可以在#temp中插入此值并添加where子句comma_sep_feature =' 10,20'如下所示

SELECT ID,
        stuff(
        (
            select ','+ convert(varchar,feature) from yourtable where Id = t.Id for XML path('')
        ),1,1,'') [comma_sep_feature]
        into #tem
        FROM [yourtable] t 
        group by id

    select * from #tem where comma_sep_feature = '10,20'

    drop table #tem