使用group by子句计算行数

时间:2014-04-01 12:04:36

标签: database postgresql

我已经在表格中找到了问卷调查的答案,并且我想要计算某个responses到某个campaign的唯一cr_answers。最好在一个(子)查询中

这些是相关表格

cr_campaign id,name,..... meta ....

cr_answers id,campaign_id,response_id,question_id,answer,ts
其中response_id是每个响应的唯一标识符,56 | 1 | 'efghays' | 34 | 'Answer' | 2014-04-01 13:59:08 57 | 1 | 'efghays' | 35 | 'Answer to other question' | 2014-04-01 13:59:08 58 | 1 | 'zlxkjgh' | 34 | 'Answer by other person' | 2014-03-30 15:45:35 表中有多个tupple 例如:

counts

我尝试了这个查询,但子查询返回的行多了一行,因为它SELECT *, ( SELECT count(*) FROM cr_answers WHERE campaign_id = cr_campaign.id GROUP BY response_id ) as responses FROM cr_campaign ORDER BY actief 组中的tupples而不是返回的行总数。

{{1}}

1 个答案:

答案 0 :(得分:2)

对于ID为_id

的特定广告系列
select count(distinct response_id) as responses
from
    cr_answers a
    inner join
    cr_campain c on a.campaign_id = c.id
where c.id = _id

适用于所有广告系列

select c.id, count(distinct response_id) as responses
from
    cr_answers a
    inner join
    cr_campain c on a.campaign_id = c.id
group by c.id
order by c.id