2

我有一个 sql 查询,在其中我有一个计算贡献保证金的计算字段。我让它显示并且数学工作正常。我遇到的问题是我只想显示贡献保证金低于 0.25 的记录。我知道您不能在 where 子句中使用列别名。我想知道这样做的最佳方法是什么。我也在为此使用 Visual Studio。

4

4 回答 4

4
SELECT  *
FROM    (
        SELECT  m.*,
                compute_margin(field1, field2) AS margin
        FROM    mytable m
        ) q
WHERE   margin < 0.25
于 2011-03-24T16:52:03.257 回答
1

您不能使用列别名(除非您将原始查询用作子查询),但您可以使用您正在使用的表达式来定义计算值。

例如,如果您的查询现在是这样的:

select
    contribution_amount,
    total_amount,
    contribution_amount / total_amount as contribution_margin

from records

你可以这样做:

select
    contribution_amount,
    total_amount,
    contribution_amount / total_amount as contribution_margin

from records

where contribution_amount / total_amount < 0.25

或这个:

select * from
(
    select
        contribution_amount,
        total_amount,
        contribution_amount / total_amount as contribution_margin

    from records
)
where contribution_margin < 0.25

(我个人认为第一个版本更可取,但两者的性能可能相同)

于 2011-03-24T16:52:07.060 回答
0

你可以

  • 在 where 子句中重复计算
  • 将查询包装在表表达式(CTE 或派生表)中,并在 where 子句中使用别名
  • 在 a 中分配别名cross apply

举最后一种方法的例子

select doubled_schema_id,*
from sys.objects
cross apply (select schema_id*2 as doubled_schema_id) c
where doubled_schema_id= 2
于 2011-03-24T16:52:19.900 回答
0

两种方式,Quassnoi 发布的解决方案(您也可以使用类似的 CTE)

或者WHERE compute_margin(field1, field2) < 0.25

于 2011-03-24T16:53:17.523 回答