我需要划分销售员Yes
和产品Pen
超过 销售总额(在我的情况下为8)并获得总百分比。
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
我被困在缺失的部分上:
select concat(100 * count(missing this piece) / count(Sale_Number), '%')
as "Salesman Sales for Pens"
from mytable
where Salesman_Used = 'Yes'
and Product = 'Pen'
我尝试的问题是where clause
也会影响Sale_Number
..我该怎么做?提前谢谢。
答案 0 :(得分:2)
您可以使用子查询来获取销售条目的总数:
select concat(100 * count(*) / (select count(*) from mytable), '%')
as "Salesman Sales for Pens"
from mytable
where Salesman_Used = 'Yes'
and Product = 'Pen'
答案 1 :(得分:2)
试试这个:
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'
答案 2 :(得分:2)
聚合有filter
子句:
如果指定了FILTER,那么只有filter_clause求值为true的输入行被送入聚合函数;其他行被丢弃。
所以:
select concat(100 * count(*) filter (where Salesman_Used = 'Yes' and Product = 'Pen') / count(Sale_Number), '%')
as "Salesman Sales for Pens"
from mytable
答案 3 :(得分:1)
我从未使用过Postgresql,但也许这样有效:
select concat(100 * (select count(*) from mytable) / count(Sale_Number), '%')
as "Salesman Sales for Pens"
from mytable
where Salesman_Used = 'Yes'
and Product = 'Pen'