选择字段包含特定项目和其他任何项目

时间:2017-01-06 15:48:06

标签: sql

说我有下表

ID | Trans_id 
1  | 10
2  | 20 
2  | 20
2  | 20
2  | 20
2  | 10
3  | 20
4  | 20
5  | 10
6  | 10

如何选择trans_id包含20 具有另一个不同数字的ID,无论它是什么(在此示例中,我应仅返回ID 2)?

4 个答案:

答案 0 :(得分:2)

您可以使用聚合和having

select id
from t
group by id
having sum(case when trans_id = 20 then 1 else 0 end) > 0 and
       sum(case when trans_id <> 20 then 1 else 0 end) > 0;

答案 1 :(得分:2)

或者,使用exists

Select distinct Id from table t
Where trans_id = 20
   and exists (Select * from table 
               Where ID = t.Id
                  and trans_id != 20)

答案 2 :(得分:1)

您可以使用此查询:

SELECT ID
FROM Table1
WHERE ID IN (SELECT DISTINCT ID FROM Table1 WHERE Trans_id = 20)
GROUP BY ID
HAVING COUNT(DISTINCT(Trans_id)) > 1

子查询仅选择包含Trans_id = 20的ID,GROUP BY ID + HAVING COUNT(DISTINCT(Trans_id)) > 1确保此组中还有其他Trans_id。

答案 3 :(得分:-1)

这将有效:

   SELECT DISTINCT ID FROM MyTable WHERE Trans_id = 20