使用sql,如何同时计算属性的已过滤和未过滤的出现次数?

使用sql,如何同时计算属性的已过滤和未过滤的出现次数?,sql,Sql,所以这可能是一个简单的问题,但问题来了。我有一些经过过滤的数据,这些数据是通过如下查询获得的: SELECT DISTINCT account_id, count(*) as filtered_count FROM my_table WHERE attribute LIKE '%filter%' GROUP BY account_id ORDER BY account_id 这给了我一个有两列的输出表 我想添加第三列 count(*) as total_count 统计整个表中每个帐户i

所以这可能是一个简单的问题,但问题来了。我有一些经过过滤的数据,这些数据是通过如下查询获得的:

SELECT DISTINCT account_id, count(*) as filtered_count 
FROM my_table
WHERE attribute LIKE '%filter%'
GROUP BY account_id
ORDER BY account_id 
这给了我一个有两列的输出表

我想添加第三列

count(*) as total_count
统计整个表中每个帐户id出现的总次数(忽略筛选器)


如何编写此三列表的查询?

您可以在count函数中放入大小写表达式,然后删除where子句:

SELECT account_id, 
        count(case when attribute LIKE '%filter%' then 1 end) as filtered_count,
        count(*) as total_count
FROM my_table
GROUP BY account_id
ORDER BY account_id;

使用
DISTINCT
虽然实际上对您的查询没有危害,但由于分组的原因是多余的,因此我已将其删除。

您可以在count函数中放置一个大小写表达式,然后删除where子句:

SELECT account_id, 
        count(case when attribute LIKE '%filter%' then 1 end) as filtered_count,
        count(*) as total_count
FROM my_table
GROUP BY account_id
ORDER BY account_id;

使用
DISTINCT
虽然实际上对您的查询没有危害,但由于分组的原因是多余的,因此我已将其删除。

您必须使用case语句对过滤器进行计数:

SELECT DISTINCT account_id, 
count(case when attribute LIKE '%filter%' then 1 else null end) as filtered_count,
count (*)
FROM my_table
GROUP BY account_id
ORDER BY account_id 

您必须使用case语句与过滤器一起计数:

SELECT DISTINCT account_id, 
count(case when attribute LIKE '%filter%' then 1 else null end) as filtered_count,
count (*)
FROM my_table
GROUP BY account_id
ORDER BY account_id 

如果我只想显示过滤计数不等于0的条目,该怎么办?从我现在拥有的这个新表中进行选择的最佳方法是什么?然后使用
HAVING
来过滤-->
HAVING count(当属性为“%filter%”时,则为1 end)>0
如果我只想显示过滤后的计数不等于0的条目怎么办?从我现在拥有的这个新表中进行选择的最佳方法是什么?然后使用
HAVING
来筛选-->
HAVING count(当属性为“%filter%”时,则为1 end)>0