SQL:创建临时变量

时间:2013-09-15 10:22:33

标签: sql sql-server

我是SQL的新手,所以请考虑这个 noob 问题。此外,我很尴尬地承认我无法在Google中搜索正确的关键字,而且我已经没时间了,所以我决定在这里问一下。

代码:

select
 *,
 price * quantity as [Total price],
 case
   when [Total price]>100 and [Total price]<= 200 then '2%'
   when [Total price]>200 and [Total price]<= 300 then '3%'
   when [Total price]>300 and [Total price]<= 400 then '4%'
   else '0%'
 end as tax
from
grocery

正如你所看到的,我想要做的是尝试在执行SQL语句时创建一个临时变量但是,这个给了我错误

Error 1: could not prepare statement [1 no such column: Total price]

我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

快速的方法是使用CTE(公用表表达式)。这允许您预先计算一些值,然后引用查询正文中的值。

如果使用CTE的陈述不是批次中的第一件事,则需要使用;结束前面的内容:

 ;
 With Totals as
 (
    select  *,
            price * quantity as [Total price],
    from    grocery
 )
 select  *
    ,  case
         when [Total price]>100 and [Total price]<= 200 then '2%'
         when [Total price]>200 and [Total price]<= 300 then '3%'
         when [Total price]>300 and [Total price]<= 400 then '4%'
        else '0%'
     end as tax
 from
   Totals

顺便提一下,问题的根源在于您无法定义表达式,然后在查询中使用表达式 by name 。您可以重复使用表达式,但不能使用名称:

select  x + 1 as Expr1
   ,    (x + 1) * 2  as Expr2
from   Table1

这样可行,但以下不会工作:

select x + 1 as Expr1
   ,   Expr1 * 2 as Expr2   -- This won't work
from   Table1

答案 1 :(得分:1)

SELECT *,
 case
   when [Total price]>100 and [Total price]<= 200 then '2%'
   when [Total price]>200 and [Total price]<= 300 then '3%'
   when [Total price]>300 and [Total price]<= 400 then '4%'
   else '0%'
 end as tax
FROM (SELECT *, price * quantity as [Total price]
      FROM grocery) A

OR

select
 *,
 price * quantity as [Total price],
 case
   when price * quantity >100 and price * quantity<= 200 then '2%'
   when price * quantity>200 and price * quantity<= 300 then '3%'
   when price * quantity>300 and price * quantity<= 400 then '4%'
   else '0%'
 end as tax
from
grocery