根据多个相关计数返回值

时间:2018-02-01 16:36:25

标签: sql oracle count

我正在寻找一个查询,该查询只返回一个不是所有者的个人客户和两个或更多公司客户,而这些客户也不是所有者。

因此,对于下面的数据,它应该返回' 103'

ACCNO  CUST_ID  OWNER     TYPE
 101     ABB      N     Personal
 101     CDD      N     Personal
 101     EFF      N     Corporate
 103     GHH      N     Personal
 103     IJJ      N     Corporate
 103     KLL      N     Corporate
 103     MNN      N     Corporate
 105     OPP      Y     Personal
 105     QRR      N     Corporate
 105     STT      N     Corporate
 106     UVV      Y     Personal
 106     WXX      Y     Corporate
 107     YZZ      N     Personal
 107     XYY      N     Corporate

感觉需要执行多项计数,条件是将它们连接在一起,然后在帐号上加以区别,但我不知道从哪里开始。

总结一下,如果它有帮助:

返回帐号,其中count(Type = Personal和Owner = N)= 1并且count(Type = Corporate and Owner = N)> 1

2 个答案:

答案 0 :(得分:1)

你必须通过计算进行分组。一个例子

   select accno
from table1
where type = 'Corporate' and owner = 'N'
and accno in (
     select accno
     from table1
     where type = 'Personal' and owner = 'N'
     group by accno
     having count(*) = 1
)
group by accno
having count(*) > 1;

您可以根据您的数据找到此处的sqlfiddle: http://sqlfiddle.com/#!4/416bfb/11

答案 1 :(得分:1)

OP中的“摘要”就是答案本身。使用COUNT(CASE ...)根据某些条件对值进行计数,并在HAVING子句中使用:

SELECT accno
FROM table1
WHERE owner = 'N'
GROUP BY accno
HAVING COUNT(CASE WHEN TYPE = 'Personal' THEN 1 END) = 1
AND COUNT(CASE WHEN TYPE = 'Corporate' THEN 1 END) >= 2;