选择查询以返回记录,其中列A具有一对多关系列B - ORA-00937错误

时间:2013-08-16 19:18:16

标签: sql oracle oracle-sqldeveloper

我正在尝试编写一个返回所有记录的查询,其中第一列的值映射到第二列中的多个不同值。我尝试了以下但是得到了“不是单组组功能”。我在这里做错了什么?

select contact_id, count(location_account_id)
from
(select a.contact_id, a.location_account_id
from crm.asset_plus a 
where a.contact_id is not null
group by a.contact_id, a.location_account_id)
having count(location_account_id) > 1

2 个答案:

答案 0 :(得分:0)

将HAVING子句移动到子查询中,并在子查询SELECT中包含计数。

Select  SQ.contact_id
from    (
        select  a.contact_id
                ,count(a.location_account_id)
        from    crm.asset_plus a 
        where   a.contact_id is not null
        group by 
                a.contact_id
        having  count(a.location_account_id) > 1
        ) SQ

如果您需要在最终输出中包含计数 - 那么只需使用子查询本身。

根据以下评论,这是一个修订后的查询,它计算locatin_account_id的DISTICT

Select  SQ.contact_id
from    (
        select  a.contact_id
                ,count(distinct a.location_account_id)
        from    crm.asset_plus a 
        where   a.contact_id is not null
        group by 
                a.contact_id
        having  count(distinct a.location_account_id) > 1
        ) SQ

答案 1 :(得分:0)

这是你想要做的吗?

SELECT contact_id, location_account_id
FROM crm.asset_plus a 
JOIN (
    SELECT contact_id, location_account_id
    FROM crm.asset_plus 
    WHERE a.contact_id is not null
    GROUP BY contact_id
    HAVING count(1) > 1
) X ON X.asset_plus  = A.asset_plus  AND X.location_account_id = A.location_account_id