首页 > 解决方案 > SQL Server:获取其他列都具有相同值的列值

问题描述

在下面的示例中,我在获取所需内容时遇到问题。

我的数据:

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

我似乎无法得到我需要的东西。任何帮助,将不胜感激!

标签: sqlsql-servertsql

解决方案


您可以使用group by子句:

select AnotherId
from table t
group by AnotherId
having min(status) = max(status) and min(status) = 'new';      

推荐阅读