在 SQL 服务器中选择一个组内的所有记录
Selecting one vs all records within group in SQL Server
我在 SQL 服务器中有一个 table 类似这样的东西(这些记录稍后来自用户输入我必须加入这个 table 与业务 table)
Table一个
id
组
项目
1
一个
4567876
2
一个
5678988
3
一个
9999999
4
B
1234567
5
B
6846677
对于我想要的每个组 select,如果项目 9999999 有任何条目,则 select 只有该记录,否则该组中的所有记录。 (例如,对于 A 组 select 项目 9999999 和 B 组所有项目的给定示例)
id
组
项目
3
一个
9999999
4
B
1234567
5
B
6846677
我不想从 table 中删除任何记录。
您可以使用 not exists
:
select a.*
from a
where a.item = 9999999 or
not exists (select 1
from a a2
where a2.group = a.group and
a2.item = 9999999
);
你也可以使用 rank()
的奇特技巧:
select top (1) with ties t.*
from t
order by rank() over (partition by group
order by (case when item = 9999999 then 1 else 2 end)
);
我在 SQL 服务器中有一个 table 类似这样的东西(这些记录稍后来自用户输入我必须加入这个 table 与业务 table)
Table一个
id | 组 | 项目 |
---|---|---|
1 | 一个 | 4567876 |
2 | 一个 | 5678988 |
3 | 一个 | 9999999 |
4 | B | 1234567 |
5 | B | 6846677 |
对于我想要的每个组 select,如果项目 9999999 有任何条目,则 select 只有该记录,否则该组中的所有记录。 (例如,对于 A 组 select 项目 9999999 和 B 组所有项目的给定示例)
id | 组 | 项目 |
---|---|---|
3 | 一个 | 9999999 |
4 | B | 1234567 |
5 | B | 6846677 |
我不想从 table 中删除任何记录。
您可以使用 not exists
:
select a.*
from a
where a.item = 9999999 or
not exists (select 1
from a a2
where a2.group = a.group and
a2.item = 9999999
);
你也可以使用 rank()
的奇特技巧:
select top (1) with ties t.*
from t
order by rank() over (partition by group
order by (case when item = 9999999 then 1 else 2 end)
);