Reputation: 826
I need to divide where Salesman is Yes
and Product is Pen
over the total amount of sales (in my case is 8) and get the total percentage.
select * from mytable
Sale_Number Date Salesman_Used Product
1 01/01/2014 No Pen
2 01/02/2014 No Pen
3 01/03/2014 Yes Pen
4 01/04/2014 Yes Pencil
5 01/05/2014 Yes Pen
6 01/06/2014 Yes Pencil
7 01/07/2014 No Pencil
8 01/08/2014 No Pencil
I am stuck on the missing piece:
select concat(100 * count(missing this piece) / count(Sale_Number), '%')
as "Salesman Sales for Pens"
from mytable
where Salesman_Used = 'Yes'
and Product = 'Pen'
The problem with my attempt is that the where clause
affects the Sale_Number
as well.. How can I do this? Thanks in advance.
Upvotes: 1
Views: 1078
Reputation: 15624
There is filter
clause for an aggregates:
If FILTER is specified, then only the input rows for which the filter_clause evaluates to true are fed to the aggregate function; other rows are discarded.
So:
select concat(100 * count(*) filter (where Salesman_Used = 'Yes' and Product = 'Pen') / count(Sale_Number), '%')
as "Salesman Sales for Pens"
from mytable
Upvotes: 2
Reputation: 766
Try this:
select concat(100 * count(missing this piece) / count(select Sale_Number from mytable), '%')
as "Salesman Sales for Pens"
from mytable
where Salesman_Used = 'Yes'
and Product = 'Pen'
Upvotes: 2
Reputation: 35164
You could use a subquery to get the overall count of sales entries:
select concat(100 * count(*) / (select count(*) from mytable), '%')
as "Salesman Sales for Pens"
from mytable
where Salesman_Used = 'Yes'
and Product = 'Pen'
Upvotes: 2
Reputation: 1822
I have never used Postgresql but maybe this works:
select concat(100 * (select count(*) from mytable) / count(Sale_Number), '%')
as "Salesman Sales for Pens"
from mytable
where Salesman_Used = 'Yes'
and Product = 'Pen'
Upvotes: 1