简体   繁体   English

SQL 返回错误值(?)

[英]SQL returns wrong value (?)

SQL Case statement with formula returns the wrong value in the column. SQL 带有公式的案例语句返回列中的错误值。 What I am trying to do is to calculate the absolute value based on several conditions.我要做的是根据几个条件计算绝对值。 First of all when the risk_class is either "Not enough samples" or "Regular price" the absolute value should be zero.首先,当 risk_class 为“样本不足”或“正常价格”时,绝对值应为零。 Secondly, when the difference between the mode and the price is less than zero, the absolute value should be zero.其次,当模式与价格的差异小于零时,绝对值应为零。 If all these conditions are not met, then the risk_abs should be the difference between the mode and price multiplied by the quantity column corresponding with the row.如果不满足所有这些条件,那么 risk_abs 应该是 mode 和 price 之间的差值乘以该行对应的数量列。

UPDATE dbo.import_company
SET risk_abs = ROUND(t.risk_abs, 0)
FROM (
        SELECT invoice_ref, risk_class, modus, price, quantity, 
        CASE
            WHEN risk_class = 'Onvoldoende observaties' THEN 0
            WHEN risk_class = 'Gefactureerd tegen reguliere prijs' THEN 0
            WHEN (modus - price) < 0 THEN 0
            ELSE (modus - price) * quantity
        END AS risk_abs
        FROM dbo.import_company
)
t WHERE t.invoice_ref = dbo.import_company.invoice_ref


SELECT invoice_ref, article_code, quantity, price, modus, risk_class, risk_abs
FROM dbo.import_company
WHERE risk_class = 'Gefactureerd tegen reguliere prijs'

I don't understand why me result is different, and the formulas don't work.我不明白为什么我的结果不同,并且公式不起作用。 See below见下文

图片示例

I don't get how the 140 is calculated and why it ignores all statements?我不明白 140 是如何计算的,为什么它会忽略所有语句?

Any advice and tips on what I am doing wrong are welcome!欢迎任何关于我做错的建议和提示!

There's no aggregation here or any other reason I can see to use a subquery to do the CASE logic.这里没有聚合或我可以看到使用子查询来执行CASE逻辑的任何其他原因。 So we can get rid of that and the too-loose attempt at correlation between the subquery and the table:所以我们可以摆脱这个以及子查询和表之间过于松散的关联尝试:

UPDATE dbo.import_company
SET risk_abs = ROUND(CASE
        WHEN risk_class = 'Onvoldoende observaties' THEN 0
        WHEN risk_class = 'Gefactureerd tegen reguliere prijs' THEN 0
        WHEN (modus - price) < 0 THEN 0
        ELSE (modus - price) * quantity
    END, 0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM