5

我是 SQL 新手,所以请考虑这个菜鸟问题。此外,承认我无法在 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]

我怎么能这样做?

4

2 回答 2

4

一种快速的方法是使用 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

顺便说一句,您的问题的根源是您不能定义一个表达式,然后在查询中按名称使用该表达式。您可以重复使用表达式,但不能按名称:

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
于 2013-09-15T10:27:48.003 回答
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

或者

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
于 2013-09-15T10:29:12.243 回答