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

その都市に関連するすべてのレコードが持っている都市を返したいのですStatus=1が、そのレコードの1つにStatus<>1その都市が結果セットから除外されている場合。このシナリオでは、都市を返したい: 1 , 3.

Sql クエリまたは LINQ クエリでこれを行うにはどうすればよいですか?

ありがとう

4

6 に答える 6

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

お役に立てれば。

于 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 のグループ句の仕事のように見えます。

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 に答える