【问题标题】:SQL Select only duplicates from one columnSQL 仅从一列中选择重复项
【发布时间】:2014-08-25 12:10:09
【问题描述】:

我有一个查询会生成这样的表:

BN      System  amount
13098   System1 860.05
16722   System1 63360
16722   System2 1544713.19000001
01292   System2 3260
17133   System2 6240
33851   System2 155340.03
24638   System2 11364.54
89936   System1 3719.85
57522   System2 50153558.7400001
84197   System2 6175
81568   System2 57402.05
99029   System2 59108.88
97532   System1 880
13283   System2 16745.51
51553   System2 26222
77632   System2 9202.5
84314   System2 185750
84314   System1 233766.5

这是我用来获取此表的查询:

select 
    BN,
    System,
    SUM(Amount)
FROM 
    tbl1
group By
    BN,
    System

我只想选择具有重复 BN 的行。

例如,我想在 BN = 16722 和 BN = 84314 时返回。

我该怎么做?

我尝试过使用

Having count(BN) > 1

但它不起作用。

【问题讨论】:

    标签: sql tsql sql-server-2012 duplicates


    【解决方案1】:
    select t.bn, t.system, sum(t.amount)
      from tbl1 t
      join (select bn from tbl1 group by bn having count(distinct system) > 1) x
        on t.bn = x.bn
     group by t.bn, t.system
    

    我认为“重复”是指相同的 BN 值与 2 个以上的唯一系统相关联?

    如果是这种情况,上面应该可以工作。

    【讨论】:

      【解决方案2】:

      我认为最好的方法是使用窗口函数:

      select t.*
      from (select t.*, count(*) over (partition by system)) as cnt
            from tbl t
           ) t
      where cnt > 1;
      

      如果您确实在使用子查询,这将特别有用。这个公式只运行一次子查询。

      【讨论】:

        【解决方案3】:

        这是使用exists 的另一种方式。

        select bn, system, sum(amount)
        from tbl1 t1
        where exists (select 1 from tbl1 t2 
            where t1.bn = t2.bn and t1.system <> t2.system)
        group by bn, system
        

        【讨论】:

          猜你喜欢
          • 2018-02-22
          • 2013-12-22
          • 1970-01-01
          • 1970-01-01
          • 2021-04-01
          • 2014-01-20
          • 2014-11-26
          • 2018-07-30
          • 2020-10-16
          相关资源
          最近更新 更多