如何在 sql 计算中使用变量

How to use variables in sql calculations

我小table

[db2inst1@dashmpp-head-0 - Db2wh ~]$ db2 "select * from TEX"

C1                   C2        
-------------------- ----------
                1000 2000      

  1 record(s) selected.

我正在尝试使用 case 语句进行如下小计算:

SELECT c1,
CASE
    WHEN c1 > 0 THEN 10
    WHEN c1 = 30 THEN 5
    ELSE 1
END AS QuantityText,
c2,
100 / QuantityText as UTILIZATION
FROM TEX;

这个查询的语法是正确的,但是当我 运行 这个时,我得到:

SQL0206N  "QUANTITYTEXT" is not valid in the context where it is used.  
SQLSTATE=42703

无需计算,以下查询 运行 没问题:

[db2inst1@dashmpp-head-0 - Db2wh ~]$ db2 "SELECT c1,
> CASE
>     WHEN c1 > 0 THEN 'The quantity is greater than 30'
>     WHEN c1 = 30 THEN 'The quantity is 30'
>     ELSE 'The quantity is under 30'
> END AS QuantityText,
> c2
> FROM TEX;"

C1                   QUANTITYTEXT                    C2        
-------------------- ------------------------------- ----------
                1000 The quantity is greater than 30 2000      

  1 record(s) selected.

我是 sql 的新手,我不确定自己做错了什么。如何在计算中使用QuantityText?如果我对查询中的文本进行硬编码,它就可以正常工作。

我尝试了什么:

  1. 已添加100 / @QuantityText as UTILIZATION
  2. 已添加100 / bigint(double(QuantityText)) as CPU_UTILIZATION
    SELECT c1,
    c2,
    100 / QuantityText as UTILIZATION FROM (
    CASE
      WHEN c1 > 0 THEN 10
      WHEN c1 = 30 THEN 5
      ELSE 1
    END AS QuantityText,
    TEX);

SQL0104N  An unexpected token "CASE       WHEN" was found following 
"UTILIZATION FROM ( ".  Expected tokens may include:  "<select>".  
SQLSTATE=42601

您可以使用 table 表达式来“命名”您生成的表达式,这样您就可以在外部查询中进一步使用它。

例如:

select
  *,
  100 / QuantityText as UTILIZATION -- used here
from (
  SELECT c1,
  CASE
    WHEN c1 > 0 THEN 10
    WHEN c1 = 30 THEN 5
    ELSE 1
  END AS QuantityText, -- named here
  c2
  FROM TEX
) x