I would like to add a relative percentage to an SQL output
Here is the code:
SELECT customer_status.status AS "Status of Customer",
COUNT (customer_bio),
FROM customer_status
JOIN customer_bio
ON customer_status.status_id=customer_bio.status_id
GROUP BY status
Here is the output
Status | Number |
---|---|
Switched Off | 352 |
Out of Town | 743 |
Not reachable | 564 |
Active | 13738 |
Relocated | 78 |
I want to add percentage on another column where by switched off is 352/total number * 100
I tried this:
SELECT customer_status.status AS "Status of Customer",
count(customer_bio)
count(customer_bio)/count(*) * 100 AS "Percentage
FROM customer_status
JOIN customer_bio
ON customer_status.status_id=customer_bio.status_id
GROUP BY status
|nd this is what I get:
Status | Number | Percentage |
---|---|---|
Switched Off | 352 | 100 |
Out of Town | 743 | 100 |
Not reachable | 564 | 100 |
Active | 13738 | 100 |
Relocated | 78 | 100 |
Please assist. I use postgresql via azure data studio
2
Answers
Both
COUNT(customer_bio)
andCOUNT(*)
give you the same output because they’re both aggregated on the same partition (GROUP BY status
).You can try using window functions instead. Since window functions compute values for each record, you can then remove duplicate rows with the
DISTINCT
operator.please try this way: