使用带有案例陈述的子查询

时间:2015-06-16 15:18:51

标签: sql-server-2008 case

这可能无法实现,如果是这样,我将如何重新编写查询以达到相同的结果?我一直收到这个错误:

  

Msg 130,Level 15,State 1,Line 2   无法对包含聚合或子查询的表达式执行聚合函数。

这是我的语法

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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。