0

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

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
4

2 回答 2

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
于 2013-08-16T19:26:18.000 回答
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

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

根据下面的评论,这里是一个修改后的查询,它计算DISTICTlocatin_account_id 的值

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
于 2013-08-16T19:19:40.033 回答