2015-06-16 70 views
0

這可能是不可能實現的,如果是的話,我將如何重新編寫我的查詢以獲得相同的結果?我不斷收到此錯誤:使用帶查詢語句的子查詢

Msg 130, Level 15, State 1, Line 2 Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

這是我的語法

select 
count(case when username in (select username from database0254.dbo.userinformation) then 1 else 0 end) As [Active User] 
,count(case when name in (select fullname from database0254.dbo.names) then 1 else 0 end) As [Valid Name] 
From users 

回答

1

雖然還有其他方法,並且可以作出其他的改進, 你應該能夠簡單地將你的邏輯部分移動到一個通用表格表達式(CTE)中:

WITH cte AS (
    select case when username in (select username from database0254.dbo.userinformation) then 1 else 0 end As [Active User] 
      ,case when name in (select fullname from database0254.dbo.names) then 1 else 0 end As [Valid Name] 
    From users 
) 
SELECT SUM([Active User]) [Active User] 
     ,SUM([Valid Name]) [Valid Name] 
    FROM cte 

注意:我們將您的COUNT更改爲SUM。

2

試試這個:

select sum(case when ui.username is null then 0 else 1) As [Active User] 
      ,sum(case when n.fullname is null then 0 else 1) As [Valid Name] 
from  users u 
left join database0254.dbo.userinformation ui on u.username = ui.username 
left join database0254.dbo.names n on u.name = u.fullname