在一个(子)查询中使用别名进行计算

时间:2018-04-06 22:08:45

标签: mysql

我有一个包含数据的表,我正在尝试在查询中进行以下计算:IDO / IDP * 100.

**TBL**
Name    IDP    IDO
ABC     123    231
DEF     124    NULL
GHI     125    NULL
JKL     126    342
KNM     127    NULL

我设法计算了进行计算所需的所有值,并给每个值一个别名。这是我到目前为止,但计算部分返回一个错误,告诉我不支持引用。

SELECT
    SUM(case when IDP is not null then 1 end) as Checked,
    SUM(case when IDO is null then 1 end) as NotChecked,
        (SELECT Checked / NotChecked) * 100 AS Result
FROM TBL 

我也试过了一个子查询,但它会导致同样的错误。

SELECT
        SUM(case when IDP is not null then 1 end) as Checked,
        SUM(case when IDO is null then 1 end) as NotChecked,
            (
              SELECT Checked / NotChecked * 100 AS Result FROM TBL
            )
        FROM TBL 

这样做的正确或更好的方法是什么?

1 个答案:

答案 0 :(得分:2)

我认为您不能在同一个SELECT子句中引用SELECT子句中创建的别名。

您可能知道,您可以重复逻辑,如下所示(尽管我假设您的问题的目的是避免编写逻辑两次)。

SELECT
    SUM(case when IDP is not null then 1 end) as Checked,
    SUM(case when IDO is null then 1 end) as NotChecked,
        (SUM(case when IDP is not null then 1 end) / SUM(case when IDO is null then 1 end)) * 100 AS Result
FROM TBL 

子查询版本,您不重复逻辑,如下所示。请注意,别名是在子查询中创建的,因此外部查询可以引用它们。

SELECT
 Checked, NotChecked, (Checked / NotChecked) * 100 as Result
FROM
(
 SELECT
    SUM(case when IDP is not null then 1 end) as Checked,
    SUM(case when IDO is null then 1 end) as NotChecked
 FROM TBL 
) tt

由于你似乎没有求和,只计算null /非null值,我个人觉得sum / case语句有点令人困惑,可能更喜欢这样的东西:

SELECT
 Checked, NotChecked, (Checked / NotChecked) * 100 as Result
FROM
(
 SELECT
    count(IDP) as Checked,
    count(*)-count(IDO) as NotChecked
 FROM TBL 
) tt