2017-03-13 173 views
0

所以我正在從現有表中讀取一些信息並創建一個新變量(wgtdiff),它是原始數據表中兩個變量的差異,然後將它們放入因爲我想知道有多少人口有0-5,5-10等的差別......我想要的是能夠顯示出多少百分比的人口屬於哪個桶(比如說0-5被認爲是一個桶)。我找到了原始表格的例子,並嘗試過並且沒有奏效。我可以計算一個我剛創建的變量嗎?下面是我有:在相同的結果集內對新創建的變量進行SQL計數

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

只需使用一個子查詢:

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 
+0

我改變了'CASE'語句的'... THEN'部分,這些'5.01和10'之間的條件可能是危險的。 [所以你可能不需要再使用'round'了。] –

+0

嗨Giorgos,爲了糾正。 – Winky

+0

嗨Giorgos,爲更正 - 我認爲用<=取代使它更清潔。因此,現在我所擁有的是一個名爲CASE的新列,其中包含指定的文本值,例如'0至+/- 5'。當你說使用子查詢時,是否意味着我必須先完成我已經完成的工作,然後將其寫入新表格中,然後選擇包含字段CASE的TABLENEW,然後從TABLENEW中選擇並創建一個新字段以保持計數很多'0到5','5到10'?我的最終目標是能夠獲得像帕累託圖表一樣的報告,以查看準確切割產品的百分比。謝謝 – Winky

相關問題