Sql 如何检查字段中的所有记录是否具有相同的值?
为这个新手问题道歉 我有如下数据:Sql 如何检查字段中的所有记录是否具有相同的值?,sql,Sql,为这个新手问题道歉 我有如下数据: ID|SubID|Category 1|1|Fixed 1|2|Fixed 2|1|Unfixed 2|2|Unfixed 3|1|Fixed 4|1|Unfixed 5|1|Fixed 5|2|Unfixed 我需要知道所有子ID的类别为“固定”的所有ID(即,我希望查询返回ID 1和3) 我该怎么做 作为一个扩展,我需要知道类别中包含所有子ID的“固定”和“未固定”组合的所有ID(即,我希望查询只返回ID 5) 提前谢谢 如果不存在具有未固定ID的行,则
ID|SubID|Category
1|1|Fixed
1|2|Fixed
2|1|Unfixed
2|2|Unfixed
3|1|Fixed
4|1|Unfixed
5|1|Fixed
5|2|Unfixed
我需要知道所有子ID的类别为“固定”的所有ID(即,我希望查询返回ID 1和3)
我该怎么做
作为一个扩展,我需要知道类别中包含所有子ID的“固定”和“未固定”组合的所有ID(即,我希望查询只返回ID 5)
提前谢谢 如果不存在具有未固定ID的行,则返回ID:
select distinct ID
from tablename t1
where not exists (select 1 from tablename t2
where t2.id = t1.id
and t2.Category = 'Unfixed')
问题2,固定和未固定混合:
select id
from tablename
group by id
having max(Category) <> min(Category)
选择id
从表名
按id分组
具有最大(类别)最小(类别)
也就是说,对于一个ID,返回两个不同类别的ID。这对于一个
存在的来说非常容易做到
(仅适用于固定的<代码>
)
对于两者的混合:
Select Distinct T.ID
From Table T
Where Exists
(
Select *
From Table T2
Where T2.ID = T.ID
And T2.Category = 'Fixed'
)
And Exists
(
Select *
From Table T2
Where T2.ID = T.ID
And T2.Category = 'Unfixed'
)
您可以使用分组by
+having
子句
我需要知道所有子ID的类别为“固定”的所有ID
我需要知道类别中包含所有子ID的“固定”和“未固定”组合的所有ID
Select Distinct T.ID
From Table T
Where Exists
(
Select *
From Table T2
Where T2.ID = T.ID
And T2.Category = 'Fixed'
)
And Exists
(
Select *
From Table T2
Where T2.ID = T.ID
And T2.Category = 'Unfixed'
)
select id
from tablename
group by id
having count(*) = count(case when Category = 'Fixed' then 'X' end)
select id
from tablename
group by id
having count(distinct Category) = 2