如何检查所有记录在字段中是否具有相同的值?

时间:2015-09-23 13:36:21

标签: 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"固定"对于所有SubID(即我希望查询返回ID 1和3)。

我该怎么做?

一个扩展,我需要知道所有类别包含"固定" AND"没有固定"对于所有SubID(即我希望查询只返回ID 5)。

提前致谢!

3 个答案:

答案 0 :(得分:1)

您可以使用group by + having条款。

  

我需要知道所有SubIDs的“固定”类别的所有ID

select id
  from tablename
 group by id
 having count(*) = count(case when Category = 'Fixed' then 'X' end)
  

我需要知道所有子ID包含“固定”和“未固定”混合的所有ID

select id
  from tablename
 group by id
 having count(distinct Category) = 2

答案 1 :(得分:0)

如果不存在具有未固定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。

答案 2 :(得分:0)

使用EXISTS非常容易。

(对于那些只有Fixed

的人
Select  Distinct T.ID
From    Table   T
Where Not Exists
(
    Select  *
    From    Table   T2
    Where   T2.ID = T.ID
    And     T2.Category = 'Unfixed'
)
And Exists
(
    Select  *
    From    Table   T2
    Where   T2.ID = T.ID
    And     T2.Category = 'Fixed'
)

两者兼而有之:

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'
)
相关问题