有3张表,presms(preid,content),detail(preid,detailid),mt(detailid,status(有0和1两个状态)),presms与detail是一对多的关系,数据表现形式为:presms中有一条记录,那么detail表可以有很多记录对presms的那一条记录进行描述,他们是通过preid关联的,detail与mt是一对一的关系,mt表有一个字段是status来描述与detail表相关记录的状态的,表就是这样设计的,请不要讨论合不合理了,这两张表是通过detailid关联的。现在需查询出这样一个显示结果(这4列),
preid content preid在detail中对应的行数 preid在detail中对应行数中在取status为0的行数。 要求,只需一条SQL。
select t2.preid, t2.content, t1.numb
from (select d.preid prid, count(*) numb
from detail d, mt m
where d.detailid = m.detailid
and m.status = 0
group by d.preid) t1,
presms t2
where t1.prid = t2.preid
select a.preid, a.content, count(1), sum(case when c.status = '0' then 1 else 0 end) from presms a, detail b, mt c where a.preid = b.preid and b.detailid = c.detailid group by a.preid, a.content
应该这样,你可以试试:
select preid,contenct,detalid,status from presms p,detalail d,mt m
where p.preid = d.preid and p.detailid=m.detailid and m.status = 0
select a.preid, a.content,sum(case when c.status=1 then 1 else 0 end)as num1 ,sum(case when c.status=0 then 1 else 0 end)as num2 from presms a, detail b, mt c where a.preid = b.preid and b.detailid = c.detailid group by a.preid
select t2.preid, t2.content,t3.c, t1.numb
from (select d.preid prid, count(*) numb
from detail d, mt m
where d.detailid = m.detailid
and m.status = 0
group by d.preid) t1,
presms t2,
(select preid,count(*) c from detail group by preid) t3
where t1.prid = t2.preid and t2.preid = t3.preid
在楼下的语句上稍作添加即可