How do I count decimal places in SQL?

前端 未结 6 729
日久生厌
日久生厌 2020-12-06 01:30

I have a column X which is full of floats with decimals places ranging from 0 (no decimals) to 6 (maximum). I can count on the fact that there are no floats with greater th

6条回答
  •  悲&欢浪女
    2020-12-06 02:18

    Here's another Oracle example. As I always warn non-Oracle users before they start screaming at me and downvoting etc... the SUBSTRING and INSTRING are ANSI SQL standard functions and can be used in any SQL. The Dual table can be replaced with any other table or created. Here's the link to SQL SERVER blog whre i copied dual table code from: http://blog.sqlauthority.com/2010/07/20/sql-server-select-from-dual-dual-equivalent/

    CREATE TABLE DUAL
    (
     DUMMY VARCHAR(1)
    )
    GO
    INSERT INTO DUAL (DUMMY)
    VALUES ('X')
    GO
    

    The length after dot or decimal place is returned by this query. The str can be converted to_number(str) if required. You can also get the length of the string before dot-decimal place - change code to LENGTH(SUBSTR(str, 1, dot_pos))-1 and remove +1 in INSTR part:

    SELECT str, LENGTH(SUBSTR(str, dot_pos)) str_length_after_dot FROM
    (
     SELECT '000.000789' as str
          , INSTR('000.000789', '.')+1 dot_pos 
       FROM dual
    )
    /
    
    SQL>
    
    STR           STR_LENGTH_AFTER_DOT
    ----------------------------------
    000.000789    6
    

    You already have answers and examples about casting etc...

提交回复
热议问题