0

I want to calculate the percentage of elected people for each member type, I was able to do this:

SELECT Member, COUNT(Name) * 100 / 
    (SELECT COUNT(*) FROM 'results' WHERE Member= '1' ) AS 'perc' 
FROM 'results' 
    WHERE elected='yes' AND Member = '1'

但我想为所有成员值做这件事(也是'0')

我的表如下所示:

Name     member     Elected
----------------------------
joe      0          yes
ann      1          no
jef      0          no

这是我想要的结果:

Member    Percentage
---------------------
0         50%
1         0%
4

4 回答 4

1

你应该能够使用这样的东西:

select member,
  coalesce(count(case when elected = 'yes' then 1 end)/count(*), 0) * 100 Percentage
from results
group by member

请参阅带有演示的 SQL Fiddle

结果:

| MEMBER | PERCENTAGE |
-----------------------
|      0 |         50 |
|      1 |          0 |
于 2013-01-03T15:03:30.597 回答
1
SELECT Member, 
   Sum(Case When elected='yes' Then 1 
            Else 0 End) / COUNT(*) 'perc' 
FROM 'results' 
group by Member
于 2013-01-03T15:04:54.750 回答
0

您的查询应该是

SELECT Member, 
(COUNT(Case When elected='yes' Then 1 Else NULL End) / COUNT(*)) * 100 'perc' 
FROM 'results'     
group by Member
于 2013-01-03T15:07:53.773 回答
0

尝试Group By Member

如果您使用sqlfiddle.com,那么很容易为您提供帮助。

bluefeet偷东西给你

select member,
  concat(FLOOR(coalesce(count(case when elected = 'yes' then 1 end)/count(*), 0) * 100), '%')  Percentage
from results
group by member
于 2013-01-03T15:10:20.383 回答