返回与该项目相关的所有记录都具有特定条件的项目

请考虑这种情况:

我有这样一张桌子:

ID City Status -------------------------------------- 1 1 1 2 1 1 3 1 1 4 2 1 5 2 0 6 3 1 7 3 1 8 3 1 9 3 1 10 4 3 11 4 1 12 4 0 

我想要返回Citis,与该城市相关的所有记录都具有Status=1并且如果其中一条记录具有Status1 ,则该城市将从reslut集中排除。 在这个场景中,我想要回归城市:1,3。

我如何使用Sql Query或LINQ查询执行此操作?

谢谢

这样的事情应该做到这一点。

LINQ:

 var citiesToExclude = context.Table .Where(t => t.Status != 1) .Select(t => t.City); var cities = context.Table .Where(t => t.Status == 1) .Where(t => !citiesToExclude.Contains(t.City)) .Select(t => t.City) .Distinct() .ToList(); 

SQL:

 SELECT City FROM [Table] WHERE Status == 1 AND City NOT IN (SELECT City FROM [Table] WHERE Status <> 1) GROUP BY City 

希望这可以帮助。

您可以使用GROUP BYHAVING进行条件聚合:

 SELECT city FROM tbl GROUP BY city HAVING COUNT(CASE WHEN status <> 1 THEN 1 END) = 0 

其他方式

 select distinct city from city C1 where city=1 and not exists(select * from city C2 where C1.city=C2.city and isnull(Status,0)<>1) 
 SELECT tbl.city FROM (SELECT c.city, count(status=1) cnt1, count() cnt2 FROM city c GROUP BY c.city) AS tbl WHERE tbl.cnt1=tbl.cnt2 AND tbl.cnt1>0 

这看起来像LINQ的group子句的工作:

 var cities = from t in table group t by t.City into grp where grp.Select(g => g.Status).All(s => s == 1) select g.Key; 

你为什么不能用这个? 该函数似乎没有聚合,因此不需要

 select city from [table] where status = 1 and city not in (select city from table where status <> 1) group by city; 

除非我误解了这个问题?