我正在 Postgres 9.3 中创建报告。这是我的SQL Fiddle .
基本上我有两个表,responses
和 questions
,结构是:
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/