我可以使用别名'例如语句

发布于 2025-01-25 21:44:14 字数 474 浏览 3 评论 0原文

SELECT 
    id
    , quantity
    , unit_price 
    , (antity * unit_price) as price    
CASE
    WHEN quantity * unit_price > 5000 THEN (quantity * unit_price) * 0.2
    WHEN quantity * unit_price > 3000 THEN (quantity * unit_price) * 0.15 
    ELSE null 
END 

AS discount

FROM OrderDetails;

我尝试在case中使用Alias Price,但它不起作用。 在上面的代码中,我重复了数量 * unit_price 5次。 是否有更好的方法来实现此代码? 有没有方法可以避免在案例语句中重复?

SELECT 
    id
    , quantity
    , unit_price 
    , (antity * unit_price) as price    
CASE
    WHEN quantity * unit_price > 5000 THEN (quantity * unit_price) * 0.2
    WHEN quantity * unit_price > 3000 THEN (quantity * unit_price) * 0.15 
    ELSE null 
END 

AS discount

FROM OrderDetails;

I tried to use the alias price in CASE but it doesn't work.
In the above code, I repeated quantity * unit_price 5 times.
Do exist any better way to realize this code?
Is there way to avoid repetition in the CASE statement?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

酷遇一生 2025-02-01 21:44:14

您可以使用CTE

WITH CTE as (
SELECT 
    id
    , quantity
    , unit_price,
    (antity * unit_price) as price
FROM OrderDetails
)
SELECT 
    id
    , quantity
    , unit_price 
    , price    
CASE
    WHEN price > 5000 THEN price * 0.2
    WHEN price > 3000 THEN price * 0.15 
    ELSE null 
END 

AS discount

FROM OrderDetails;

You could use a CTE

WITH CTE as (
SELECT 
    id
    , quantity
    , unit_price,
    (antity * unit_price) as price
FROM OrderDetails
)
SELECT 
    id
    , quantity
    , unit_price 
    , price    
CASE
    WHEN price > 5000 THEN price * 0.2
    WHEN price > 3000 THEN price * 0.15 
    ELSE null 
END 

AS discount

FROM OrderDetails;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文