Page 1 of 1

Get two percentages in a single query

Posted: Mon Jan 27, 2014 2:41 pm
by recci
Ok I have a single table called opportunities, within that table I have field called sales_stage. I need to get the percentage of rows where sales_stage is "Closed Won" and also get percentage of rows where sales_stage is "Closed Lost" And basically just display the two headings Closed won and Closed Lost.

I'm a little bit lost with how to do this one, here is an sql fiddle

http://sqlfiddle.com/#!2/ac28d/13

Re: Get two percentages in a single query

Posted: Mon Jan 27, 2014 3:13 pm
by Weirdan
This is called 'pivot': http://en.wikibooks.org/wiki/MySQL/Pivot_table

What you need is, basically:

Code: Select all

select 
   sum(sales_stage="Closed Won")/count(*) * 100 as won_pct, 
   sum(sales_stage="Closed Lost")/count(*) * 100 as lost_pct
from opportunities

Re: Get two percentages in a single query

Posted: Mon Jan 27, 2014 3:18 pm
by recci
Thanks that seems to be exaclty what I was looking for