在 SQL Snowfalke 中将正值转为负值
我有一列,其中的值描述已退回商品的价格。它们是积极的,当对它们求和时,我需要它们变成消极的。 例如:
订单 id | 商品 id | 返回 | 价格 | 数量 |
---|---|---|---|---|
123 | 456 | True | 50 | 1 |
987 | 123 | True | 10 | 2 |
下面的示例查询获取返回值的总和:
sum(case when returned = 'True' then (price * quantity) else 0 end) as returnedAmount
我的一个想法是:
sum(case when returned = 'True' then (-1*(price * quantity)) else 0 end) as returnedAmount
但是返回 null,不知道为什么。有人有更明智的建议吗?
I have a column where the values describe the price of an item that has been returned. They are positive and when sum:ing them I would need them to become negative.
Ex:
order id | item id | returned | price | quantity |
---|---|---|---|---|
123 | 456 | True | 50 | 1 |
987 | 123 | True | 10 | 2 |
Example query below to get the sum of the returned value:
sum(case when returned = 'True' then (price * quantity) else 0 end) as returnedAmount
One thought I had was:
sum(case when returned = 'True' then (-1*(price * quantity)) else 0 end) as returnedAmount
But that returned null, not sure why. Does anyone have a smarter suggestion?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果
返回
列是布尔值,则比较只是列名称:如果查询返回 NULL,则可能意味着 PRICE 或 QUANTITY 列对于组中的所有值都可为空:
If the
returned
column is boolean then comparison is just column name:If the query returns NULL it could mean that either PRICE or QUANTITY columsn are nullable for all values in a group:
所以你不需要乘以-1,你可以直接对值取反:
给出:
所以到空,所以以太值可以为空,正如卢卡斯所示,你可以在外面修复它总而言之,有几个选项 ZEROIFNULL,COALESCE,< a href="https://docs.snowflake.com/en/sql-reference/functions/nvl.html" rel="nofollow noreferrer">NVL, IFNULL。
如果你想要值为零,我觉得 Zeroifnull 是显式的,而其他三个你必须一直解析表达式到右边才能看到替代值。
给出:
so you don't need to multiply by -1 you can just negate the value:
gives:
So to the null, so ether value could null and as Lukasz showed, you can fix that on the outside of the sum, there are a few options ZEROIFNULL, COALESCE, NVL, IFNULL.
if you want the value zero, I feel zeroifnull is explicit, while the other three you have to parse the expression all the way to the right to see the alternative value.
gives: