2012-06-08 16 views
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服務器上會有所不同嗎?

任何幫助將不勝感激。

回答

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

這麼簡單! Oracle數據庫也需要同樣的東西嗎? – user1444329

+0

確實需要MySQL和SQL-Server上的別名。我也猜測Oracle,但我不確定。 –

+0

在Oracle上看起來沒有必要。看[這個例子](http://sqlfiddle.com/#!4/c55f3/3)。它適用於Oracle,不適用於將數據庫引擎更改爲其他人。 –

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 
    ) ; 
相關問題