title: How to use variables in sql calculations
body: <p>I have small table</p>
  <pre><code>[db2inst1@dashmpp-head-0 - Db2wh ~]$ db2 &quot;select * from TEX&quot;
  
  C1                   C2        
  -------------------- ----------
                  1000 2000      
  
    1 record(s) selected.
  </code></pre>
  <p>And I am trying to use case statement with a small calculation as follows:</p>
  <pre><code>SELECT c1,
  CASE
      WHEN c1 &gt; 0 THEN 10
      WHEN c1 = 30 THEN 5
      ELSE 1
  END AS QuantityText,
  c2,
  100 / QuantityText as UTILIZATION
  FROM TEX;
  </code></pre>
  <p>Syntax of this is query is correct but when I run this I get:</p>
  <pre><code>SQL0206N  &quot;QUANTITYTEXT&quot; is not valid in the context where it is used.  
  SQLSTATE=42703
  </code></pre>
  <p>Without calculations the following query runs fine:</p>
  <pre><code>[db2inst1@dashmpp-head-0 - Db2wh ~]$ db2 &quot;SELECT c1,
  &gt; CASE
  &gt;     WHEN c1 &gt; 0 THEN 'The quantity is greater than 30'
  &gt;     WHEN c1 = 30 THEN 'The quantity is 30'
  &gt;     ELSE 'The quantity is under 30'
  &gt; END AS QuantityText,
  &gt; c2
  &gt; FROM TEX;&quot;
  
  C1                   QUANTITYTEXT                    C2        
  -------------------- ------------------------------- ----------
                  1000 The quantity is greater than 30 2000      
  
    1 record(s) selected.
  </code></pre>
  <p>I am new to sql and I am not sure what am I doing wrong here. How to use <code>QuantityText</code> in calculation? If I hardcode the text in the query it works fine.</p>
  <p>What I tried:</p>
  <ol>
  <li>added <code>100 / @QuantityText as UTILIZATION</code></li>
  <li>added <code>100 / bigint(double(QuantityText)) as CPU_UTILIZATION</code></li>
  <li></li>
  </ol>
  <pre><code>    SELECT c1,
      c2,
      100 / QuantityText as UTILIZATION FROM (
      CASE
        WHEN c1 &gt; 0 THEN 10
        WHEN c1 = 30 THEN 5
        ELSE 1
      END AS QuantityText,
      TEX);
  
  SQL0104N  An unexpected token &quot;CASE       WHEN&quot; was found following 
  &quot;UTILIZATION FROM ( &quot;.  Expected tokens may include:  &quot;&lt;select&gt;&quot;.  
  SQLSTATE=42601
  </code></pre>