database - 带有 INNER JOIN 的 Postgres COUNT 列值数

标签 database postgresql count inner-join aggregate-filter

我正在 Postgres 9.3 中创建报告。这是我的SQL Fiddle .
基本上我有两个表,responsesquestions,结构是:

responses
->id
->question_id
->response

questions
->id
->question
->costperlead

response 列只能有 3 个值,Yes/No/Possbily, 我的报告应该有以下栏目:

  question_id
, # of Yes Responses
, # of No Responses
, # of Possbily Responses
, Revenue

然后:

# of Yes Responses - count of all Yes values in the response column
# of No Responses - count of all No values in the response column
# of Possbily Responses - count of all 'Possbily' values in the response column

收入是 costperlead *(是的响应数 + 可能的响应数)。

我不知道如何构建查询,我是新手,而且我来自 MySQL,所以有些事情对于 postgres 是不同的。在我的 SQL Fiddle 示例中,大多数响应是 Yes 和 Null,最终没问题,可能会有和 No。

到目前为止我只有:

SELECT a.question_id
FROM responses a
INNER JOIN questions b ON a.question_id = b.id
WHERE a.created_at = '2015-07-17'
GROUP BY a.question_id;

最佳答案

你应该尝试:

SELECT a.question_id, 
       SUM(CASE WHEN a.response = 'Yes' THEN 1 ELSE 0 END) AS NumsOfYes, 
       SUM(CASE WHEN a.response = 'No' THEN 1 ELSE 0 END) AS NumsOfNo,
       SUM(CASE WHEN a.response = 'Possibly' THEN 1 ELSE 0 END) AS NumOfPossibly,
       costperlead  * SUM(CASE WHEN a.response = 'Yes' THEN 1 ELSE 0 END) + SUM(CASE WHEN a.response = 'Possibly' THEN 1 ELSE 0 END) AS revenue
FROM responses a 
     INNER JOIN questions b ON a.question_id = b.id 
GROUP BY a.question_id, b.costperlead

关于database - 带有 INNER JOIN 的 Postgres COUNT 列值数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31514856/

相关文章:

sql - 使用 postgreSQL 将字符串转换为 CLOB

R 相当于 SQL SELECT COUNT(*) ... GROUP BY

r - 有没有办法计算 R 中整数列表范围内的整数元素的数量?

C++ Visual Studio DLL 文件

java - Tomcat H2 部署

mysql - Magento 2 安装失败 - SQLSTATE[HY000] [1045] 用户访问被拒绝

ruby-on-rails - 在 rails 和 postgresql 中使用键值进行不区分大小写的搜索

sql - 如何从postgres中的group by获取多个结果

mysql - 连续日期的计数总和

php - RedBean 是否需要 "id"主键?