[英]Select More Rows Based on Column Condition MSSQL
我正在嘗試從我的 ResourceGroup 表中檢索 ResourceGroupName 列表。 對我來說棘手的部分是,GroupsId 是 ResourceGroupId(資源組的主鍵)的子集,這意味着如果我的條件滿足 ResourceGroupName = 'A30_1RecourceGrp',我希望能夠 select 所有 ResourceGroupName 因為這個資源組有 2 個子集GroupId = '0014e68000000192' 和 '0014e6800000001b' 這是下面的兩條記錄。
而我想要達到的結果是
我的 MSSQL 知識非常有限,我找不到寫它的方法,我被困在下面的 SQL 上,它只顯示 1 個結果。
SELECT * from ResourceGroup rg
LEFT JOIN ResourceGroupGroups rgg ON rgg.ResourceGroupId = rg.ResourceGroupId
WHERE rg.ResourceGroupId = '0014e68000000002'
任何幫助深表感謝。 謝謝!
更新:
資源組表
資源組組表
您可以嘗試使用 distinct
SELECT distinct rrg.ResourceGroupName
from ResourceGroup rg
LEFT JOIN ResourceGroupGroups rgg ON rgg.ResourceGroupId = rg.ResourceGroupId
WHERE rg.ResourceGroupId = '0014e68000000002'
有一些方法可以做到(因為我不知道你的表結構是怎樣的):
1- 使用Distinct
關鍵字,如下所示
SELECT Distinct ResourceGroupName
from ResourceGroup rg
LEFT JOIN ResourceGroupGroups rgg ON rgg.ResourceGroupId = rg.ResourceGroupId
WHERE rg.ResourceGroupId = '0014e68000000002'
或以這種方式:
select Distinct ResourceGroupName from ResourceGroupGroups rgg
where rgg.ResourceGroupId in (
SELECT ResourceGroupId
from ResourceGroup rg
WHERE rg.ResourceGroupId = '0014e68000000002'
)
2-使用Group by
命令按ResourceGroupName
對結果進行分組
3-使用partition by
和row_number
窗口函數和select第一條記錄
更新:
基於有問題的ResourceGroup
表結構,您可以只查詢該表,甚至不需要加入,如下所示:
select ResourceGroupName
from ResourceGroup
where ResourceGroupId = '0014e68000000002'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.