在同一结果集中对新创建的变量进行SQL计数

时间:2017-03-13 21:52:55

标签: sql count

所以我从现有表中读取一些信息并创建一个新变量(wgtdiff),这是原始数据表中2个变量的差异,然后将它们分组,因为我想知道多少人口的差异为0-5,5-10等......而我想要的是能够显示出百分之百的人口属于哪个桶(让我们说0- 5是考虑一个桶子。我找到了原始表计数的例子,但尝试过并且没有用。我可以算一个刚创建的变量吗?这就是我所拥有的:

select heat_no as HeatNo, grade_id as Grade, strand_no as Strand,
       cast_seq as CastSeq, billet_weight as bli_billet_weight,
       plc_weight as bli_plc_weight, billet_date as bli_billet_date,
       round ((bli_plc_weight - bli_billet_weight),2) as Wgtdiff_plc_aim,
       CASE WHEN abs(round((bli_plc_weight - bli_billet_weight),2)) <= 5 THEN '0 to +/- 5'
            WHEN abs(round((bli_plc_weight - bli_billet_weight),2)) between 5.01 and 10 THEN '+/- 5 to 10'
            WHEN abs(round((bli_plc_weight - bli_billet_weight),2)) between 10.01 and 15 THEN '+/- 10 to 15'
            WHEN abs(round((bli_plc_weight - bli_billet_weight),2)) between 15.01 and 20 THEN '+/- 15 to 20'
            Else 'Greater than +/- 20'
       END as CASE
from Billet_table

1 个答案:

答案 0 :(得分:0)

只需使用子查询:

select HeatNo, Grade, Strand, CastSeq, bli_billet_weight, bli_plc_weight, bli_billet_date,Wgtdiff_plc_aim
CASE WHEN abs(round((bli_plc_weight - bli_billet_weight),2)) <= 5 THEN '0 to +/- 5'
    WHEN abs(round((bli_plc_weight - bli_billet_weight),2)) <= 10 THEN '+/- 5 to 10'
    WHEN abs(round((bli_plc_weight - bli_billet_weight),2)) <= 15 THEN '+/- 10 to 15'
    WHEN abs(round((bli_plc_weight - bli_billet_weight),2)) <= 20 THEN '+/- 15 to 20'
    Else 'Greater than +/- 20'
END as CASE
from (select heat_no as HeatNo, grade_id as Grade, strand_no as Strand,
           cast_seq as CastSeq, billet_weight as bli_billet_weight,
           plc_weight as bli_plc_weight, billet_date as bli_billet_date,
           round ((plc_weight - billet_weight),2) as Wgtdiff_plc_aim
     from Billet_table) temp