所以这可能是一个简单的问题,但是这里有。我有一些通过这样的查询得到的过滤数据:
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
计算整个表中每个account_id的出现次数(忽略过滤器)。
如何为这三列表编写查询?
答案 0 :(得分:3)
您可以在count函数中放置一个case表达式,然后删除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
虽然实际上对您的查询没有任何影响,但由于分组而导致多余,因此我已将其删除。
答案 1 :(得分:1)
您必须使用案例陈述来计算过滤器:
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