对出现在多个资料中的账号进行单独统计。

问题描述 投票:3回答:3

我有一个表,里面有账号(account_num)和用户配置文件(profile_id)。不同的配置文件可以有多个相同账号的实例,或者一个配置文件有多个不同账号的实例。(不能有多个具有相同帐号的配置文件实例)。

我试图写一个查询,给我一个不同的帐号数,这些帐号出现在多个配置文件中。

我尝试了下面的查询(尽管我希望能得到更有效的查询建议)。

Select Count(*) from
(select account_num, count(profile_id) as num_users
from dbo.sample
where account_num <> ''
group by account_num
)
where num_users >1

但我一直得到以下错误。

Msg 156, Level 15, State 1, Line 7
Incorrect syntax near the keyword 'where'.

我使用的是Microsoft SQL Server Management Studio。作为一个旁观者,这个查询在Oracle服务器上会有所不同吗?

任何帮助将是非常感激的。

sql sql-server distinct
3个回答
2
投票

尝试将子查询别名为

 select Count(*) from 
    (   
        select account_num, count(profile_id) as num_users 
        from dbo.sample 
        where account_num <> '' group by account_num
    ) t 
 where num_users > 1

0
投票

你想要的结果也可以通过这个查询来显示。

SELECT COUNT(DISTINCT account_num) AS cnt
FROM dbo.sample    a                        --- no AS here to work in Oracle
WHERE account_num <> ''
  AND profile_id IS NOT NULL
  AND EXISTS
      ( SELECT *
        FROM dbo.sample    b 
        WHERE b.account_num = a.account_num
          AND profile_id IS NOT NULL
          AND b.PK <> a.PK                  --- the PRIMARY KEY of the table
      ) ;
© www.soinside.com 2019 - 2024. All rights reserved.