简体   繁体   English

MySQL案例无效ROUND值

[英]MySQL Case not working ROUND the value

I'm trying to ROUND() or not the selected value. 我正在尝试ROUND()或不是所选的值。 The query looks likes this: 查询看起来像这样:

SELECT  b.Series,
        CASE 
            WHEN Series = 'DMS' THEN ROUND(b.Quantity,0)
            ELSE ROUND(b.Quantity,2)
        END AS Quantity
        FROM bill b

I also tried 我也试过了

CASE Series
     WHEN 'DMS' THEN ROUND(b.Quantity,0)
     ELSE ROUND(b.Quantity,2)
END AS Quantity,

and

IF(b.Series = 'DMS', ROUND(b.Quantity,0), ROUND(b.Quantity,2)) AS Quantity,

Every time I get the 2 decimals at the end. 每次我在最后得到2位小数。

When the Series is 'DMS' Quantity should be like an integer (without decimals), in the other cases Quantity should have two decimals. Series为'DMS'时, Quantity应该像一个整数(不含小数),在其他情况下, Quantity应该有两个小数。

In a result set, the data type is an attribute of the column for the entire result set. 在结果集中,数据类型是整个结果集的的属性。

For any given column in a result set, the value in that column for each row must necessarily be of the same data type. 对于结果集中的任何给定列,每列中该列的值必须具有相同的数据类型。

The data type of the returned column for this query will, by necessity, be set by the server to something along the lines of DECIMAL(11,2) in order to accommodate all the possible values. 必要时,此查询的返回列的数据类型将由服务器设置为DECIMAL(11,2) ,以便容纳所有可能的值。

I would anticipate that what you are seeing is actually correctly rounded, but with an "unexpected" .00 at the end. 我预计你所看到的实际上是正确的四舍五入,但结尾有一个“意外的” .00

CAST(CASE ... END AS CHAR) AS Quantity would -- potentially -- get you a result that looks more like you're expecting, by casting everything to a string. CAST(CASE ... END AS CHAR) AS Quantity - 可能 - 通过将所有内容都转换为字符串来获得看起来更像您期望的结果。

That's obviously some very sloppy type-handling, but it's no more unreasonable than expecting different types to emerge in the same column... which can't be done. 这显然是一些非常草率的类型处理,但它并不比预期不同类型出现在同一列中更不合理......这是不可能完成的。

The more correct solution is to return them as two different columns, with two CASE expressions or IF() . 更正确的解决方案是将它们作为两个不同的列返回,使用两个CASE表达式或IF()

ROUND(IF(Series = 'DMS',b.Quantity,NULL),0) AS dms_quantity,
ROUND(IF(Series = 'DMS',NULL,b.Quantity),2) AS non_dms_quantity

Note that both IF() tests evaluate the same expression and have their arguments reversed rather than the second one using != with the arguments the same, so that NULL values for series, if possible, are handled correctly by the second test. 请注意,两个IF()测试都评估相同的表达式并使其参数反转而不是使用!=且参数相同的第二个参数,因此,如果可能,系列的NULL值将由第二个测试正确处理。 (Anything != NULL cannot evaluate to true; the third argument to IF() is used for both FALSE AND NULL results). (Anything!= NULL无法求值为true; IF()的第三个参数用于FALSE和NULL结果)。

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

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