gpt4 book ai didi

SQL:创建临时变量

转载 作者:行者123 更新时间:2023-12-03 03:24:15 25 4
gpt4 key购买 nike

我是 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 语句时创建一个临时变量,但是,这给了我错误

错误 1:无法准备报表 [1 没有这样的列:总价]

我怎样才能做到这一点?

最佳答案

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

关于SQL:创建临时变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18811265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com