Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 包含子查询的表达式上的聚合函数_Sql_Tsql_Subquery_Case_Aggregate Functions - Fatal编程技术网

Sql 包含子查询的表达式上的聚合函数

Sql 包含子查询的表达式上的聚合函数,sql,tsql,subquery,case,aggregate-functions,Sql,Tsql,Subquery,Case,Aggregate Functions,使用以下t-sql查询: 选择u.userid 变成临时工 来自用户u 其中u.type=1; 选择前50名 contentid, 将*计算为所有_视图, sumcase从temp中选择userid中的hc.userid,然后1 else 0作为第一个计数结束, sumcase当40615、40616中的hc.userid然后1 else 0作为另一个_计数结束时 从HITCH u.userid=hc.userid上的内部加入用户u 按hc.contentid分组 按计数*描述排序; 我收到一条

使用以下t-sql查询:

选择u.userid 变成临时工 来自用户u 其中u.type=1; 选择前50名 contentid, 将*计算为所有_视图, sumcase从temp中选择userid中的hc.userid,然后1 else 0作为第一个计数结束, sumcase当40615、40616中的hc.userid然后1 else 0作为另一个_计数结束时 从HITCH u.userid=hc.userid上的内部加入用户u 按hc.contentid分组 按计数*描述排序; 我收到一条错误消息

无法对包含聚合或子查询的表达式执行聚合函数

但是,如果只包含列'other_count'和硬编码的标识符列表,那么一切都会像我预期的那样工作。有没有办法只获取子查询中包含的用户ID的计数?我计划有多个列,每个列计算不同用户ID的集合/子查询


在这一点上,性能不是一个问题,我非常感谢您的指导。

您不需要临时表格。只需使用条件聚合:

select top 50 contentid,
       count(*) as all_views,
       sum(case when u.type = 1 then 1 else 0 end) as first_count,
       sum(case when hc.userid in (40615, 40616) then 1 else 0 end) as another_count
from hitcounts hc join
     user u
     on u.userid = hc.userid
group by hc.contentid
order by count(*) desc;

在大多数情况下,您可以用左连接替换子查询,并进行条件聚合。但对于您的查询,@GordonLinoff的答案更直接、更简单。@astentx一般来说,我会在存在的情况下提出一个案例。。。然后,1在APPLY中结束并计数,因为否则,由于多行从联接中出来,您可能会得到不正确的结果。