【问题标题】:Using SELECT for columns and results to calculate third column使用 SELECT 列和结果来计算第三列
【发布时间】:2015-04-12 18:43:28
【问题描述】:

我有一条 SQL 语句,其中我对第 1 列和第 2 列使用 select 语句。这些列返回 2 个数字。

看起来像这样

SELECT column1, column2, (SELECT a FROM...) as num1,
  (SELECT b FROM...) as num2, (num1/num2) as num3

我的问题是,当我尝试使用 num1 和 num2 来计算 num3 时,我收到一条错误消息,提示 num1/num2 不是列。如何使用这些结果来计算 num3?

【问题讨论】:

  • 您收到错误,因为在获得结果后将生成列名(别名)。因此它们只能在 ORDER 语句中使用,例如

标签: sql sql-server sql-server-2008


【解决方案1】:

另一种方法是使用外部应用,如果你有很多列,这通常会更好,所以你不必全部重复:

SELECT 
  column1, column2,
  n1.a, n2.b, n3.c
FROM table1
outer apply (SELECT a FROM...) as n1
outer apply (SELECT b FROM...) as n2
outer apply (select case when n2.b != 0 then n1.a / n2.b end as c) as n3

还添加了除以零的检查。没有对此进行测试,但希望没问题。

【讨论】:

    【解决方案2】:

    您可以创建一个包含 num1 和 num2 的子查询,然后计算 num3

    select T.*, (num1/num2) as num3
    FROM
    (
        SELECT 
          column1, column2, 
          (SELECT a FROM...) as num1, 
          (SELECT b FROM...) as num2, 
        FROM table1
    ) T
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-26
      • 2021-09-08
      • 2014-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多