请考虑这种情况:
我有一张这样的表:
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
,并且其中一条记录中有Status<>1
该城市从reslut集中排除。在这种情况下,我想回归城市:1,3。
如何使用Sql Query或LINQ查询执行此操作?
感谢
答案 0 :(得分:4)
这样的事情应该这样做。
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
希望这有帮助。
答案 1 :(得分:2)
您可以简单地将GROUP BY
和HAVING
与条件聚合一起使用:
SELECT city
FROM tbl
GROUP BY city
HAVING COUNT(CASE WHEN status <> 1 THEN 1 END) = 0
答案 2 :(得分:1)
另一种方式
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)
答案 3 :(得分:0)
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
答案 4 :(得分:0)
为什么你不能用它?该函数似乎没有聚合,因此不需要having
select city
from [table]
where status = 1
and city not in
(select city from table where status <> 1)
group by city;
除非我误解了这个问题?
答案 5 :(得分: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;