1

请考虑这种情况:

我有一张这样的桌子:

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 查询来做到这一点?

谢谢

4

6 回答 6

4

像这样的事情应该这样做。

林克:

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

希望这可以帮助。

于 2012-07-17T05:27:54.710 回答
2

您可以简单地使用GROUP BYandHAVING条件聚合:

SELECT   city
FROM     tbl
GROUP BY city
HAVING   COUNT(CASE WHEN status <> 1 THEN 1 END) = 0
于 2012-07-17T05:31:33.257 回答
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)
于 2012-07-17T05:44:04.837 回答
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
于 2012-07-17T05:31:55.330 回答
0

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

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

除非我误解了这个问题?

于 2012-07-17T05:47:35.473 回答
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;
于 2012-07-17T05:53:57.410 回答