在sql中组合多个计数查询

时间:2017-02-22 19:38:03

标签: mysql sql postgresql

我有一个用户的表,其中有3列我正在尝试计算,然后按created_at date分组。

列:'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;

2 个答案:

答案 0 :(得分:4)

您应该尝试将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;

答案 1 :(得分:1)

您可以尝试将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;