仅在count == 2 SQL Server 2008时选择

时间:2010-12-08 21:17:59

标签: sql sql-server tsql

我想只选择另一个选择== 2

的条件

例如

select field1 from table1 where count((select field2 from table2)) = 2

这可能吗?

3 个答案:

答案 0 :(得分:2)

select field1 from table1 where (select count(field2) from table2)=2

答案 1 :(得分:2)

您应该查看SQL GROUP BY的{​​{3}}。

e.g。

SELECT * FROM TABLE1
WHERE <MYKEY> IN (
   SELECT <MYKEY>
   FROM TABLE2
   GROUP BY <MYKEY> HAVING COUNT(*) = 2 --Better to use > 1
)

答案 2 :(得分:1)

尝试一下:

SET NOCOUNT ON
declare @a table (RowID int)
insert @a values(1);insert @a values(2);insert @a values(3);
declare @b table (RowID int)
insert @b values(10);insert @b values(20)
SET NOCOUNT OFF

select a.RowID FROM @a a WHERE 2=(SELECT COUNT(RowID) FROM @b)

delete @b where RowID=20

select a.RowID FROM @a a WHERE 2=(SELECT COUNT(RowID) FROM @b)

输出:

RowID
-----------
1
2
3

(3 row(s) affected)

(1 row(s) affected)

RowID
-----------

(0行(s)受影响)