SQL查询数

时间:2018-08-27 18:05:48

标签: sql oracle

我正在尝试对以下数据进行SQL查询,需要从customer表中获取所有数据,其中customer_id分配了多个业务单位。

CustomerId  AccoutNo  UniqueCode  Owner p  AdminFlag  EmpId  Dept
----------  --------  ----------  -------  ---------  -----  ----
1                234         009      N        N         67   ABC
1                234         009      N        Y        232   ABC
1                234         009      Y        N         65   ABC
2                123         100      N        Y         73   PQR
2                123         100      N        N       7335   PQR
3                456         123      Y        N        633   ABC
3                789         123      Y        N       6363   ABC
1                456         009      N        Y       5674   PQR

1 个答案:

答案 0 :(得分:1)

这是解析函数(在本例中为解析函数count(distinct ...))的完美应用。在内部查询中,您可以计算每个客户有多少个不同的部门;也可以单独运行子查询,以查看其产生的结果。然后,外部查询仅选择计数大于1的行。

select customer_id, account_no -- , ... - whatever other columns you must select
from   (
         select *, count(distinct dept) over (partition by customer_id) as ct
         from   customers
       )
where  ct > 1
;  

注意-如果DEPT可以是NULL,则这些行都不会以任何方式计入count(distinct ...)中。如果NULL可能存在并且需要不同的处理方式,则需要说明该要求。