Jake Wagner
Jake Wagner

Reputation: 826

Calculate Interval of Payments

I request your assistance in finding the count and percent of customers who had certain amount payments due. I am using SQL Server 2016.

select customer_id,payments from mytable 


Customer_ID             Payments
   1                     $50
   2                     $100
   3                     $500
   4                     $550
   5                     $500
   6                     $500
   7                     $500
   8                     $400
   9                     $550
   10                    $400

Results Requested:

 Count              Percent                     Payments
   1                   10%                        $50
   2                   20%                        $400
   4                   40%                        $500
   2                   20%                        $550 
   1                   10%                        $100

Upvotes: 0

Views: 70

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269753

I think you want a window function:

select payment, count(*),
       count(*) * 1.0 / sum(count(*)) over () as ratio
from t
group by payment;

Upvotes: 0

Ilyes
Ilyes

Reputation: 14928

You can do like

SELECT COUNT(Payments) [Count],
       CAST(COUNT(Payments) * 100 / (SELECT COUNT(*) FROM T) AS VARCHAR) + '%' [Percent],
       Payments
FROM T
GROUP BY Payments;

Demo

Upvotes: 1

Related Questions