有四张表
[questions]问题选项表qid int  问题选项ID
sid int  所属调查项目ID
type int 问题选项类型
name varchar 问题名称示例数据334,7,1,'A姓名'
335,7,3,'A性别'
336,6,1,'B姓名'
337,6,3,'B性别'[effects]选项子项表当问题选项ptype是单选或多选时用eid int 选项子项ID
qid int 问题选项ID
etext varchar 选项子项名称
evalue varchar 选项子项值,指向answers表的text示例数据1,335,'A男','A性别的值0'
2,335,'A女','A性别的值1'
3,335,'B男','B性别的值0'
4,335,'B女','B性别的值1'
[identits]用户提交结果表iid int 用户提交结果ID
sid int 所属调查项目ID
isverify bit 是否通过验证
示例数据123,7,1
124,7,1
125,7,0 //没有通过验证的记录
126,7,1 
[answers]结果表关联表aid int 标志ID
iid int 用户提交结果ID
sid int 所属调查项目ID
qid int 问题选项ID
text varchar 问题回答内容
示例数据1,123,7,335,'A性别的值0'
2,124,7,335,'A性别的值1'
3,125,7,335,'A性别的值1'
4,125,7,335,'A性别的值1'现想根据qid=335查询出,通过验证的子选项的汇总结果,要求结果如下:{qid,etext,sum}335,'A男',1
335,'A女',2  //过滤了一条未通过难证的的值求SQL语句

解决方案 »

  1.   

    select a.qid,c.etext,count(*)  from #questions a left join #answers b on  a.qid=b.qid
    left join #effects c on b.text=c.evalue
    left join #identits d on b.iid=d.iid
    where a.qid=335 and isverify=1
    group by a.qid,c.etext
            qid etext                           
    ----------- -------------------- -----------
            335 A男                             1
            335 A女                             1(2 行受影响)怎么不一样。。
      

  2.   

    ----trydeclare @questions table (qid int,sid int,type int,name varchar(50))
    insert into @questions select 334,7,1,'A姓名'
                union all  select 335,7,3,'A性别'
                union all  select 336,6,1,'B姓名'
                union all  select 337,6,3,'B性别'
    declare @effects table (eid int,qid int,etext varchar(10),evalue varchar(50))
    insert into @effects select 1,335,'A男','A性别的值0'
              union all  select 2,335,'A女','A性别的值1'
              union all  select 3,335,'B男','B性别的值0'
              union all  select 4,335,'B女','B性别的值1'
    declare @identits table (iid int,sid int,isverify bit)
    insert into @identits select 123,7,1
               union all  select 124,7,1
               union all  select 125,7,0
               union all  select 126,7,1
    declare @answers table (aid int,iid int,sid int,qid int,text varchar(50))
    insert into @answers select 1,123,7,335,'A性别的值0'
             union all   select 2,124,7,335,'A性别的值1'
             union all   select 3,125,7,335,'A性别的值1'
             union all   select 4,126,7,335,'A性别的值1'
    select a.qid,etext ,次数=count(*) from 
       (select c.qid,a.etext,b.iid from @effects a join @answers b on a.qid=b.qid 
           and a.evalue=b.text and a.qid=335 
           join @questions c on a.qid=c.qid) a  where 
           not exists ( select 1 from @identits where isverify=0 and a.iid=iid)
      group by  a.qid,etext qid         etext      次数
    ----------- ---------- -----------
    335         A男         1
    335         A女         2(2 行受影响)