选择1个字段的计数大于值的位置,另一个的计数小于值

时间:2015-03-13 21:35:16

标签: sql count group-by

我正在尝试返回一个Customers表中的所有实例,其中statustype =' dc'那么对于那些结果,FC的计数是> 1,地址1上的计数为1。

IE:

FC    Address1
111    abc
111    cde
432    qqq
432    qqq

我需要111 FC结果,因为他们的地址1不同。但我不需要返回432 FC结果,因为该FC的地址超过1个

 SELECT *
  FROM Customers
  where FC IN( select FC from Customers where StatusType= 'dc'
  group by FC having COUNT(FC) > 1 and COUNT(Address1) < 2

)
  order by FC, Address1

我也试过= 1而不是&lt; 2

3 个答案:

答案 0 :(得分:1)

如果您需要有关具有多个唯一地址的FC的详细信息,那么此查询将为您提供:

select c.* from customers c
join (
    select FC
    from customers
    where statustype = 'dc'
    group by fc having count(distinct Address1) > 1
) a on c.FC = a.FC

答案 1 :(得分:0)

您还需要按地址分组。

SELECT *
FROM Customers
where FC IN( select FC from Customers where StatusType= 'dc'
group by FC, Address1 having COUNT(FC) > 1 and COUNT(Address1) < 2)
order by FC, Address1

答案 2 :(得分:0)

尝试使用Distinct COUNT

SELECT *
FROM   Customers
WHERE  FC IN(SELECT FC
             FROM   Customers
             WHERE  StatusType = 'dc'
             GROUP  BY FC
             HAVING Count(DISTINCT Address1) > 1)
ORDER  BY FC,
          Address1