[英]Select More Rows Based on Column Condition MSSQL
I'm trying to retrieve a list of ResourceGroupName from my ResourceGroup Table.我正在尝试从我的 ResourceGroup 表中检索 ResourceGroupName 列表。 The tricky part to me is, GroupsId is subset of ResourceGroupId (Primary Key for Resource Group), which means I want to be able to select all the ResourceGroupName if my condition meets ResourceGroupName = 'A30_1RecourceGrp' because this resource group has 2 subsets which are GroupId = '0014e68000000192' and '0014e6800000001b' which is the 2 records below.
对我来说棘手的部分是,GroupsId 是 ResourceGroupId(资源组的主键)的子集,这意味着如果我的条件满足 ResourceGroupName = 'A30_1RecourceGrp',我希望能够 select 所有 ResourceGroupName 因为这个资源组有 2 个子集GroupId = '0014e68000000192' 和 '0014e6800000001b' 这是下面的两条记录。
This is the table that I need to SELECT FROM这是我需要 SELECT FROM 的表
And the result I wanted to achieve is而我想要达到的结果是
MY MSSQL knowledge is very limited and I couldn't find a way to write it, I'm stucked at the SQL below and it only shows 1 result.我的 MSSQL 知识非常有限,我找不到写它的方法,我被困在下面的 SQL 上,它只显示 1 个结果。
SELECT * from ResourceGroup rg
LEFT JOIN ResourceGroupGroups rgg ON rgg.ResourceGroupId = rg.ResourceGroupId
WHERE rg.ResourceGroupId = '0014e68000000002'
Any help is much appreciated.任何帮助深表感谢。 Thank you!
谢谢!
Update:更新:
ResourceGroup Table资源组表
ResourceGroupGroups Table资源组组表
You could try using distinct您可以尝试使用 distinct
SELECT distinct rrg.ResourceGroupName
from ResourceGroup rg
LEFT JOIN ResourceGroupGroups rgg ON rgg.ResourceGroupId = rg.ResourceGroupId
WHERE rg.ResourceGroupId = '0014e68000000002'
There are some ways to do it(cause I don't know how is your structure of tables is):有一些方法可以做到(因为我不知道你的表结构是怎样的):
1- Use the Distinct
keyword like below 1- 使用
Distinct
关键字,如下所示
SELECT Distinct ResourceGroupName
from ResourceGroup rg
LEFT JOIN ResourceGroupGroups rgg ON rgg.ResourceGroupId = rg.ResourceGroupId
WHERE rg.ResourceGroupId = '0014e68000000002'
or in this way:或以这种方式:
select Distinct ResourceGroupName from ResourceGroupGroups rgg
where rgg.ResourceGroupId in (
SELECT ResourceGroupId
from ResourceGroup rg
WHERE rg.ResourceGroupId = '0014e68000000002'
)
2- use the Group by
command to group your result by ResourceGroupName
2-使用
Group by
命令按ResourceGroupName
对结果进行分组
3- use partition by
and row_number
windowing functions and select 1st records 3-使用
partition by
和row_number
窗口函数和select第一条记录
Update:更新:
Based on the ResourceGroup
table structure in question, you can just query on this table and even don't need to join, like below:基于有问题的
ResourceGroup
表结构,您可以只查询该表,甚至不需要加入,如下所示:
select ResourceGroupName
from ResourceGroup
where ResourceGroupId = '0014e68000000002'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.