没有嵌套选择,我无法执行此查询

时间:2015-05-30 15:31:17

标签: mysql sql

我有一个包含三个属性的表(identifyicator,id_law,surname,vote)。 投票可以采取三个价值观:积极,反对或弃权。

我无法执行此查询: 你想知道每一项法律,因为有正面,反对和弃权的投票。

select必须是唯一的,不允许嵌套选择

1 个答案:

答案 0 :(得分:0)

create table house_law
(   -- the proposed up for vote
law_id varchar(50) NOT NULL PRIMARY KEY,
descr varchar(255)
);

insert house_law (law_id,descr) values ('HR-109B','Forbid driving near turtles');

create table house_rep
(   -- a session is say Monday to Friday, captures a start date
rep_id int not null PRIMARY KEY,
fullname varchar(80) not null,
party varchar(80)
);

insert house_rep (rep_id,fullname,party) values (1001,'Thomas Jefferson','Whig');
insert house_rep (rep_id,fullname,party) values (800,'fred','Abstain Party');
insert house_rep (rep_id,fullname,party) values (700,'stan','Abstain Party');

create table votes_cast
(law_id varchar(50) not null,
rep_id int not null,
the_vote varchar(20) -- for, against, abstain
);

insert votes_cast (law_id,rep_id,the_vote) values ('HR-109B',1001,'against');
insert votes_cast (law_id,rep_id,the_vote) values ('HR-109B',800,'abstain');
insert votes_cast (law_id,rep_id,the_vote) values ('HR-109B',700,'abstain');

-- get the results

select l.law_id,
l.descr,
sum(case when v.the_vote='for' then 1 else 0 end) for_votes,
sum(case when v.the_vote='against' then 1 else 0 end) against_votes,
sum(case when v.the_vote='abstain' then 1 else 0 end) abstain_votes
from house_law l
join votes_cast v
on v.law_id=l.law_id
group by l.law_id -- or a where close for 1 law in particular

<强>输出: id | descr | votes_for |反对|弃权

HR-109B禁止在海龟附近驾驶0 1 2