分组求和就好了啊
select id,bid,bname,istitle,sum(bnum)
from tb
group by id,bid,bname,istitle

解决方案 »

  1.   


    但是这样写是求不出来和的呀跟直接读取表数据没什么区别呀比如select id,bid,bname,istitle,sum(bnum) as vote
    from tb
    group by id,bid,bname,istitle
    vote出来的是0啊.而不是总和
    我改成这样select id,bid,bname,istitle,sum(bnum) as vote
    from ak_vote_list where istitle=0
    group by id,bid,bname,istitle 同样是不行的
      

  2.   

    create function func_sum(@id int)
    returns int 
    as
    begin
    declare @bnums int=0
    select @bnums=sum(bnum) from tablename where istitle=@id
    return @bnums
    endselect id,bid,bname,bnum=func_sum(id),istitle from tablename where istitle=0
      

  3.   

    select a.id,a.bid,a.bname,sum(b.bnum)[bnum],a.istitle from
     ( select *from t   where  istitle=0)a left join 
    ( select *from t   where  istitle!=0)b on a.id=b.istitle group by 
    a.id,a.bid,a.bname,a.istitle第二行的记录bnum 应该是5吧。
      

  4.   

    WITH test (id,bid,type,bname,bnum,istitle) AS (
        SELECT 21,1,0,'请问你是:'      ,0,0  UNION ALL
        SELECT 22,1,0,'先生'            ,3,21 UNION ALL
        SELECT 23,1,0,'女士'            ,3,21 UNION ALL
        SELECT 24,1,0,'请问你的年龄是:',0, 0 UNION ALL
        SELECT 25,1,0,'18岁以下'        ,1,24 UNION ALL
        SELECT 26,1,0,'18-24岁'         ,3,24 UNION ALL
        SELECT 27,1,0,'24-30岁'         ,1,24
    ),
    answer AS (
        SELECT istitle,
               SUM(bnum) bnum
          FROM test
         WHERE istitle <> 0
      GROUP BY istitle
    )
    SELECT t.id,
           t.bid,
           t.bname,
           a.bnum,
           0 istitle
      FROM test t
      JOIN answer a
        ON a.istitle = t.id
             id         bid bname                   bnum     istitle
    ----------- ----------- ---------------- ----------- -----------
             21           1 请问你是:                 6           0
             24           1 请问你的年龄是:           5           0
      

  5.   

    看错了SELECT a.id,a.bid,a.bname,b.bnum,a.istitle FROM 
    (SELECT id,bid,bname,istitle
    FROM test
    WHERE istitle=0) a,
    (SELECT istitle,sum(bnum) AS bnum
    FROM test
    WHERE istitle<>0
    GROUP BY istitle) b
    WHERE a.id=b.istitle