使用INNER JOIN

时间:2015-07-20 11:04:37

标签: 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,最终确定没问题,可能会出现错误。

到目前为止,我只有:

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;

2 个答案:

答案 0 :(得分:3)

你应该尝试:

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

答案 1 :(得分:2)

由于唯一的谓词会过滤回复,因此首先汇总回复最有效,然后加入问题:

SELECT *, q.costperlead * (r.ct_yes + r.ct_maybe) AS revenue
FROM  (
   SELECT question_id
        , count(*) FILTER (WHERE response = 'Yes')      AS ct_yes
        , count(*) FILTER (WHERE response = 'No')       AS ct_no
        , count(*) FILTER (WHERE response = 'Possibly') AS ct_maybe
   FROM   responses
   WHERE  created_at = '2015-07-17'
   GROUP  BY 1
   ) r
JOIN   questions q ON q.id = r.question_id;

这使用Postgres 9.4

的新聚合Filter子句

顺便说一下,我会考虑使用response / true / falsenull作为boolean类型实施。

对于Postgres 9.3

SELECT *, q.costperlead * (r.ct_yes + r.ct_maybe) AS revenue
FROM  (
   SELECT question_id
        , count(response = 'Yes' OR NULL)      AS ct_yes
        , count(response = 'No' OR NULL)       AS ct_no
        , count(response = 'Possibly' OR NULL) AS ct_maybe
   FROM   responses
   WHERE  created_at = '2015-07-17'
   GROUP  BY 1
   ) r
JOIN   questions q ON q.id = r.question_id;

SQL Fiddle(建立在你的身上)。

以下是在存在聚合FILTER子句之前的技术比较: