限制输出group-by sql查询中的出现次数

时间:2011-08-15 15:29:29

标签: sql group-by

我有这个查询

select rep, companyname,count(companyname) as [count], Commission from customers
group by repid,companyname,Commission

它返回让我们说

rep    companyname     count    commision
1       ABC              1        10%
2       XYZ              2        10%
2       XYZ              1        20%
3       JKL              4        10%
3       JKL              1        30%

欲望输出

rep    companyname     count    commision
2       XYZ              2        10%
2       XYZ              1        20%
3       JKL              4        10%
3       JKL              1        30%

我希望有一个输出,以便我只显示那些在结果中重复两次或更多次的公司。如何修改上述查询。我使查询变得简单(删除where子句)。

5 个答案:

答案 0 :(得分:2)

我会使用子查询来获取这样的非唯一公司名称。

select rep, companyname,count(companyname) as [count], Commission from customers
where companyname in (
  select c1.companyname from customers c1
  group by c1.companyname having count(*) >= 2
)
group by repid,companyname,Commission

答案 1 :(得分:1)

我认为这符合您的要求。如果没有某种子查询或CTE,我无法想到这样做的方法:

select 
    rep, companyname, [count], commission
from (
    select 
        rep, companyname,count(companyname) as [count], Commission,
        count(1) over (PARTITION by companyname) as [companycount]
    from customers
    group by repid,companyname,Commission
) sub
where companycount > 1

答案 2 :(得分:1)

select rep
     , companyname
     , count(*) as [count]                  --- equivalent to count(companyname)
     , Commission
from customers c
where exists
      ( select *
        from customers c2
        where c2.companyname = c.companyname 
          and ( c2.repid <> c.repid
             or c2.Commission <> c.Commission 
              )
          and ( extra-conditions )
      )
  and ( extra-conditions )
group by repid, companyname, Commission

答案 3 :(得分:0)

在您的小组之后添加一个HAVING子句,例如HAVING count(companyName)&gt; 1

答案 4 :(得分:0)

您正在寻找HAVING关键字,WHERE

基本上是GROUP BY条件
select rep, companyname,count(companyname) as [count], Commission from customers
group by repid,companyname,Commission
having count(companyname) > 1