【问题标题】:How to check whether all records have the same value in a field?如何检查字段中的所有记录是否具有相同的值?
【发布时间】:2015-09-23 13:36:21
【问题描述】:

为新手问题道歉。

我的数据如下所示:

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)。

提前致谢!

【问题讨论】:

    标签: sql


    【解决方案1】:

    您可以使用group by + having 子句。

    我需要知道所有子 ID 的类别为“固定”的所有 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
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        使用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'
        )
        

        【讨论】:

          猜你喜欢
          • 2019-12-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-03-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多