【问题标题】:How to group by where at least two rows have differing column values如何按至少两行具有不同列值的位置进行分组
【发布时间】:2017-06-09 09:45:24
【问题描述】:

我有一个表,我想查询它以返回位列 IsValid 至少有两行的相反值的结果。

TableA
    UniqueId
    Column1
    Column2
    Column3
    IsValid (bit values 0 and 1)

按列 1、2、3 分组我需要返回至少有两行具有 IsValid 0 和 1 的整行。

Val1 | Val1 | Val1 | 0
Val1 | Val1 | Val1 | 1

Val2 | Val2 | Val2 | 0
Val2 | Val2 | Val2 | 1
Val2 | Val2 | Val2 | 1

Val3 | Val3 | Val3 | 0
Val3 | Val3 | Val3 | 0

将返回所有行 Val1 和 Val2,而不会返回 Val3 行。

【问题讨论】:

    标签: sql tsql group-by


    【解决方案1】:

    如果您想要所有(未聚合),那么您可以使用exists

    select a.*
    from tableA a
    where exists (select 1
                  from tableA a2
                  where a2.column1 = a.column1 and
                        a2.column2 = a.column2 and
                        a2.column3 = a.column3 and
                        isvalid = 0
                 ) and
          exists (select 1
                  from tableA a2
                  where a2.column1 = a.column1 and
                        a2.column2 = a.column2 and
                        a2.column3 = a.column3 and
                        isvalid = 1
                 );
    

    如果您想要聚合值,那么@vkp 的方法是正确的。

    【讨论】:

      【解决方案2】:

      您可以将group byhaving 一起使用。

      select column1,column2,column3
      from tableA
      group by column1,column2,column3
      having count(case when isvalid=1 then 1 end) >= 1
      and count(case when isvalid=0 then 1 end) >= 1
      

      select column1,column2,column3
      from tableA
      group by column1,column2,column3
      having min(cast(isvalid as int)) = 0 and max(cast(isvalid as int))= 1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-01
        • 2013-02-05
        • 1970-01-01
        • 1970-01-01
        • 2023-04-02
        • 1970-01-01
        • 2021-04-20
        • 1970-01-01
        相关资源
        最近更新 更多