[英]SQL Server : getting column values where other column all have same value
在下面的示例中獲取所需信息時遇到問題。
我的資料:
Id AnotherId Status
-- --------- ------
1 3 new
2 3 old
3 5 new
4 6 new
5 11 old
6 11 old
7 55 new
8 55 new
我正在尋找獨特的AnotherId
,其中每個status實例='New'
所以我的結果看起來像:
5
6
55
這將為我提供大部分幫助,但我需要所有“新”狀態記錄:
select AnotherId
from MyData
group by AnotherId
having count(distinct Status) = 1
我似乎無法確切獲得所需的東西。 任何幫助,將不勝感激!
您可以使用group by
子句:
select AnotherId
from table t
group by AnotherId
having min(status) = max(status) and min(status) = 'new';
如果您想要的只是另一個身份為new的另一個ID的清單,那么您應該可以找到那里:
SELECT DISTINCT [AnotherId]
from [MyData]
where [Status] = 'new'
and [AnotherId] NOT IN (SELECT [AnotherId] FROM [MyData] WHERE [Status] <> 'new' AND [AnotherId] IS NOT NULL)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.