Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
Node is saved as draft in My Content >> Draft
  • Percent to Total in SQL

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 33
    Comment on it

    For displaying the percent to total in SQL, we want to leverage the ideas we used for rank/running total plus subquery.

     

    Different from what we saw in the SQL Subquery section, here we want to use the subquery as part of the SELECT.

     

    Name        Sales
    
    Himanshu     10
    
    Manish       15    
    
    Prateek      20
    
    Mayank       40
    
    Suresh       50
    
    Mohan        20
    

     

     

    Then we will perform the query to get percent total

     

    SELECT a1.Name, a1.Sales, a1.Sales/(SELECT SUM(Sales) FROM Total_Sales) Pct_To_Total
    FROM Total_Sales a1, Total_Sales a2
    WHERE a1.Sales <= a2.sales or (a1.Sales=a2.Sales and a1.Name = a2.Name)
    GROUP BY a1.Name, a1.Sales
    ORDER BY a1.Sales DESC, a1.Name DESC;

     

     

    Name	       Sales	     Pct_To_Total
    
    Himanshu	50	        0.3226
    
    Manish		40              0.2581
    
    Prateek		20              0.1290
    
    Mayank		20              0.1290
    
    Suresh	        15	        0.0968
    
    Mohan	        10	        0.0645

     

    SQL Server

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: