我有两个表问答。问题答案很少。取决于" allow_multi_select"我们可以选择一个或几个问题的答案。
答案有"首选"标志。
现在我想计算允许多选答案的问题,所有选择的答案都是首选。
例如,如果问题有三个答案,其中两个是首选,我只想在选择这两个问题时计算这个问题。
如何写这样的查询?
编辑:
我的架构:
CREATE TABLE survey_question (
id BIGSERIAL PRIMARY KEY,
sid VARCHAR(32) NOT NULL,
active BOOLEAN NOT NULL DEFAULT TRUE,
question VARCHAR(2048) NOT NULL,
text_answer BOOLEAN NOT NULL DEFAULT FALSE,
multi_answers BOOLEAN NOT NULL DEFAULT FALSE,
"index" int4 NOT NULL,
survey_sid VARCHAR(32) NOT NULL,
text_answer_value TEXT,
survey_definition_question_sid VARCHAR(32) NOT NULL,
preferred_answers BOOLEAN NOT NULL,
survey_definition_sid VARCHAR(32) NOT NULL,
);
CREATE TABLE survey_answer (
id BIGSERIAL PRIMARY KEY,
sid VARCHAR(32) NOT NULL,
active BOOLEAN NOT NULL DEFAULT TRUE,
answer VARCHAR(256) NOT NULL,
"index" int4 NOT NULL,
preferred BOOLEAN NOT NULL,
survey_question_sid VARCHAR(32) NOT NULL,
survey_definition_answer_sid VARCHAR(32) NOT NULL,
);
CREATE TABLE survey_question_answer_relation (
id BIGSERIAL PRIMARY KEY,
survey_question_id int8 NOT NULL,
survey_answer_id int8 NOT NULL,
);
我没有在第一时间发布模式,因为这种模式更加适应。
答案 0 :(得分:0)
鉴于此架构
create table question (
question_id int,
allow_multi_select boolean
);
create table answer (
answer_id int,
question_id int,
preferred boolean,
selected boolean
);
在此SQL Fiddle中创建,
select count(*) as total
from (
select question_id
from
question q
inner join
answer a using (question_id)
where allow_multi_select and preferred
group by question_id
having bool_and(selected)
) s