首页 > 解决方案 > 在子查询中别名 count * 的正确方法

问题描述

我在下面有查询

select t.comment_count, count(*) as frequency 
from
(select u.id, count(c.user_id) as comment_count
from users u
left join comments c
on u.id = c.user_id 
and c.created_at between '2020-01-01' and '2020-01-31'
group by 1) t
group by 1
order by 1

当我也尝试给错误起别名count(*)count(t.*),我不能用表中的 t 来别名吗?不知道我错过了什么

谢谢

标签: sql

解决方案


Count(*)代表查询返回的所有行的计数(相对于GROUP BY列)。因此,指定所涉及的表之一是没有意义的。例如,考虑计算连接产生的行数。如果您需要特定表的行数,t您可以使用count(distinct t.<unique column>)


推荐阅读