Calculating percentages

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Paul Tennis
    New Member
    • Nov 2010
    • 6

    Calculating percentages

    Hi All,
    I have an Oracle database I am trying to run report queries against.
    I would like to calculate the ratio of a value to the sum of values in the data partition.
    The question I have is whether to use the RATIO_TO_REPORT function or the OVER and PARTITION BY functions.
    I have tried writing queries both ways and seem to get hung up on the COUNT and calculating percentages.
    Any insight is greatly appreciated.
    PaulT

    --Example Queries
    Code:
    SELECT DISTINCT ProductGroup, Product, ProductCount, (ProductCount/TotalCount) AS 'Percentage'
     From (
        Select ProductGroup, Product,
               Sum(subtotal) Over () As 'TotalCount',
               Sum(subtotal) Over (Partition By Product) As 'ProductCount'
        From Table1
        Where Product in ('Product A', 'Product B', 'Product C'))
     Where Product in ('Product A', 'Product B', 'Product C')
     Order by 1 DESC, 2;
    --Alternate Example Query
    Code:
    SELECT ProductGroup, Product, COUNT(Product),
    RATIO_TO_REPORT (SUM(Product))
    OVER (PARTITION BY Product) Percentage
    from Table1
    Where Product in ('ProductA', 'ProductB', 'ProductC')
    Group by ProductGroup, Product;

    --Example Database table:
    Code:
    ProductGroup		Product		SerialNum
    Product Group 1		Product A	S/N 12345
    Product Group 1		Product A	S/N 56789
    Product Group 1		Product B	S/N 34567
    Product Group 1		Product B	S/N 67890
    Product Group 1		Product B	S/N 98765
    Product Group 1		Product C	S/N 12312
    Product Group 1		Product C	S/N 56756
    Product Group 2		Product E	S/N 99999
    Product Group 2		Product E	S/N 88888
    Product Group 2		Product F	S/N 44444
    Product Group 2		Product F	S/N 33333
    What I would like to end up with is something which looks like this showing the count and percentage which that count represents of the subgroup:
    Code:
    ProductGroup		Product		Count	Percentage
    Product Group 1		Product A	2	.285
    Product Group 1		Product B	3	.428
    Product Group 1		Product C	2	.285
    Product Group 2		Product E	2	.5
    Product Group 2		Product F	2	.5
    Last edited by Rabbit; Feb 16 '12, 10:14 PM. Reason: Please use code tags when posting code.
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    You've over-complicated things. What you want is something like this:
    Code:
    SELECT groupField, 
       COUNT(*) AS SubCount, 
       COUNT(*) / (SELECT COUNT(*) FROM someTable) AS Percentage
    FROM someTable
    GROUP BY groupField

    Comment

    • Paul Tennis
      New Member
      • Nov 2010
      • 6

      #3
      Thanks Rabbit, it worked like a charm!

      Comment

      Working...