SQL Server 2008 - Query to get result in fraction format

后端 未结 3 1025
挽巷
挽巷 2021-01-14 05:55

I have a table which contains data like this:

MinFormat(int)  MaxFormat(int)  Precision(nvarchar)
   -2              3             1/2

The

3条回答
  •  一生所求
    2021-01-14 06:05

    Sorry, now I'm late, but this was my approach:

    I'd wrap this in a TVF actually and call it like

    SELECT * FROM dbo.FractalStepper(-2,1,'1/4');
    

    or join it with your actual table like

    SELECT *
    FROM SomeTable
    CROSS APPLY dbo.MyFractalSteller(MinFormat,MaxFormat,[Precision]) AS Steps
    

    But anyway, this was the code:

    DECLARE @tbl TABLE (ID INT, MinFormat INT,MaxFormat INT,Precision NVARCHAR(100));
    
    --Inserting two examples
    INSERT INTO @tbl VALUES(1,-2,3,'1/2')
                          ,(2,-4,-1,'1/4');
    
    --Test with example 1, just set it to 2 if you want to try the other example
    DECLARE @ID INT=1;
    
    --If you want to get your steps numbered, just de-comment the tree occurencies of "Step"
    WITH RecursiveCTE as
    (
        SELECT  CAST(tbl.MinFormat AS FLOAT) AS RunningValue
               ,CAST(tbl.MaxFormat AS FLOAT) AS MaxF
               ,1/CAST(SUBSTRING(LTRIM(RTRIM(tbl.Precision)),3,10) AS FLOAT) AS Prec
               --,1 AS Step
        FROM @tbl AS tbl
        WHERE tbl.ID=@ID
    
        UNION ALL
    
        SELECT RunningValue + Prec
              ,MaxF 
              ,Prec
              --,Step + 1
        FROM RecursiveCTE
        WHERE RunningValue + Prec <= MaxF
    )
    SELECT RunningValue --,Step 
          ,CASE WHEN CAST(RunningValue AS INT)<>RunningValue 
                THEN CAST(RunningValue / Prec AS VARCHAR(10)) + '/' + CAST(CAST(1/Prec AS INT) AS VARCHAR(MAX))
                ELSE CAST(RunningValue AS VARCHAR(10))
           END AS RunningValueFractal
    FROM RecursiveCTE;
    

    The result

    Value   ValueFractal
    -2      -2
    -1,5    -3/2
    -1      -1
    -0,5    -1/2
    0        0
    0,5      1/2
    1        1
    1,5      3/2
    2        2
    2,5      5/2
    3        3
    

提交回复
热议问题