简体   繁体   中英

MySQL Case not working ROUND the value

I'm trying to ROUND() or not the selected value. 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.

When the Series is 'DMS' Quantity should be like an integer (without decimals), in the other cases Quantity should have two decimals.

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.

I would anticipate that what you are seeing is actually correctly rounded, but with an "unexpected" .00 at the end.

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.

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() .

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. (Anything != NULL cannot evaluate to true; the third argument to IF() is used for both FALSE AND NULL results).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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