select 姓名=xm,总数=count(*),正确数=sum(case when Answer=MyAnswer then 1 else 0 end), 正确率=正确数/总数 from testhistory group by xm上面的语句执行出错:消息 207,级别 16,状态 1,第 1 行
列名 '正确数' 无效。
消息 207,级别 16,状态 1,第 1 行
列名 '总数' 无效。
我明白它是不认"正确数"和"总数"难道我非得把长长的case when重写一遍么?
有没有"人性"一些的方法?

解决方案 »

  1.   

    select 姓名=xm,
           总数=count(*),
           正确数=(select count(1) from testhistory where xm = t.xm and Answer=MyAnswer), 
           正确率=cast((select count(1) from testhistory where xm = t.xm and Answer=MyAnswer)*1.0 / count(*) as decimal(18,2))
    from testhistory t 
    group by xm
      

  2.   


    select 
    姓名=xm,
    总数=count(*),
    正确数=sum(case when Answer=MyAnswer then 1 else 0 end),
    正确率=sum(case when Answer=MyAnswer then 1 else 0 end)/count(*)
    from testhistory group by xm别称不能马上就用
      

  3.   

    难道我非得把长长的case when重写一遍么?
    有没有"人性"一些的方法?
    -------------------
    没错,无什么其它办法,或者先select into到临时表中,再对临时表select 一次
      

  4.   

    SELECT 语句执行顺序select      ---------5
    from        ----------1
    where       ----------2
    group by    ----------3
    having      ----------4
    order by    ----------6
      

  5.   


    select *,
    正确率 = 正确数 / 总数
    from (
    select
    姓名 = xm,
    总数 = count(*),
    正确数 = sum(case when Answer = MyAnswer then 1 else 0 end)
    from testhistory
    group by xm
    ) tmp
    order by 姓名