Percentage must be 100

Zaran 21 Reputation points
2021-06-08T22:19:16.55+00:00

Hi,

Could you please help me how to get the total percentage as 100% from below dataset through T-SQL?

0.66%, 0.66%, 10.63%, 21.71%, 36.84%, 23.03%, 6.48% -> must be equal 100.00%
0.61%, 0.66%, 10.65%, 21.45%, 36.48%, 23.63%, 6.76% -> must be equal 100.00%

Thanks

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,675 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Vladimir Moldovanenko 276 Reputation points
    2021-06-08T23:43:53.32+00:00

    here is one of answers, wild guess, as question is poorly formulated.

    DROP TABLE IF EXISTS #t
    
    SELECT identity (int) ID, p1.v
    INTO #t
    FROM string_split('0.66%, 0.66%, 10.63%, 21.71%, 36.84%, 23.03%, 6.48%', ',') p
    CROSS APPLY(SELECT v = TRY_CAST(REPLACE(p.value, '%','') as decimal(9,2))) p1
    
    
    SELECT 
        t.ID
        ,t.v
        ,[100%] = CASE WHEN t.ID = 1 THEN (100 - SUM(t.v)OVER()+ t.v) ELSE t.v END
    FROM #t t
    
    1 person found this answer helpful.

  2. EchoLiu-MSFT 14,591 Reputation points
    2021-06-09T02:03:36.177+00:00

    Hi @Zaran ,

    For this type of problem we recommend that you post CREATE TABLE statements for your tables together with INSERT statements with sample data.

    Since you did not describe your rules in detail, the following methods are for reference only:

    CREATE TABLE #test(val1 decimal(5,2),val2 decimal(5,2),)  
    INSERT INTO #test values(0.66,0.61),(0.66,0.66),(10.63,10.65)  
                            ,(21.71,21.45),(36.84,36.48),(23.03,23.63),(6.48,6.76)  
      
      
    SELECT CAST(ROUND(SUM(val1), 0) as varchar) + '%' as result1 ,  
    CAST(ROUND(SUM(val2), 0) as varchar) + '%' as result2  
    FROM #test  
    

    Output:
    103646-image.png

    If you have any question, please feel free to let me know.

    Regards
    Echo


    If the answer is helpful, please click "Accept Answer" and upvote it.

    0 comments No comments

  3. Tom Phillips 17,741 Reputation points
    2021-06-09T12:21:34.067+00:00

    The values you posted do not equal 100.00%. So I am unclear what you are asking.

    I assume your numbers are calculated by dividing something. In that case adding 2 decimal precision numbers together will not always equal 100.00 due to rounding. You would need to calculate your numbers to 3 decimal precision to have better luck. However, it may still not add up to 100.00. This is a common problem with percentage calculations.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.