使用带有案例语句的子查询

Use A Sub-Query With A Case Statement

这可能无法实现,如果是这样,我将如何重写我的查询以仍然获得相同的结果?我不断收到此错误:

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

试试这个:

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

虽然还有其他方法和其他改进可以进行, 您应该能够将部分逻辑简单地移动到通用的 table 表达式 (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。