在sql中组合多个计数查询

Posted

技术标签:

【中文标题】在sql中组合多个计数查询【英文标题】:combining multiple count queries in sql 【发布时间】:2017-02-22 19:38:03 【问题描述】:

我有一个用户表,其中包含 3 列,我试图对其进行计数,然后按 created_at 日期分组。

列:“created_at”、“answers_count”、“questions_count”

如何将这 3 个查询合并为一个,并将所有计数按相同的 created_at 日期分组?

这里有 3 个单独的查询:

-- daily new signups
SELECT date_trunc('day', users.created_at) AS signup_date, count(*) AS new_users
FROM users
GROUP BY signup_date
ORDER BY signup_date DESC;

-- new user answers_count by signup date
SELECT date_trunc('day', users.created_at) AS signup_date, count(*) AS answers_count
FROM users
WHERE users.answers_count > 0
GROUP BY signup_date
ORDER BY signup_date DESC;

-- new user questions_count by signup date 
SELECT date_trunc('day', users.created_at) AS signup_date, count(*) AS qs_received
FROM users
WHERE users.questions_count > 0
GROUP BY signup_date
ORDER BY signup_date DESC;

【问题讨论】:

您正在使用哪个数据库..? mysql还是postgresql? 【参考方案1】:

您应该尝试使用SUM()CASE 来完成此操作。

试试这样的:

SELECT date_trunc('day', users.created_at) AS signup_date, 
  count(*) AS new_users,
  sum(case when answers_count > 0 then 1 else 0 end) as answers_count,
  sum(case when questions_count > 0 then 1 else 0 end) as qs_received,
FROM users
GROUP BY signup_date
ORDER BY signup_date DESC;

【讨论】:

【参考方案2】:

您可以尝试使用countFILTER 来执行此操作。

SELECT date_trunc('day', users.created_at) AS signup_date, 
  count(*) AS new_users,
  count(*) FILTER (WHERE answers_count > 0) as answers_count,
  count(*) FILTER (WHERE questions_count > 0) as qs_received,
FROM users
GROUP BY signup_date
ORDER BY signup_date DESC;

【讨论】:

以上是关于在sql中组合多个计数查询的主要内容,如果未能解决你的问题,请参考以下文章

如何组合 2 个 SQL 查询并检索累积计数?

SQL聚合中同一列内的多个值的不同计数

在 SQL Server 查询中有条件地应用多个计数

如何在单个 SQL 查询中使用多个计数和按条件分组

单个 SQL 查询中的多个计数

sql [sql]使用日期过滤计算1个查询中的多个计数