我的数据如下:
joe | red
joe | red
tom | blue
joe | green
tom | red
mike | yellow
mike | green
mike | red
如何编写SQL以生成以下内容?
joe | red | 66.6%
tom | blue | 50%
joe | green | 33.3%
tom | red | 50%
mike | yellow | 33.3%
mike | green | 33.3%
mike | red | 33.3%
以下是我在微软访问SQL中尝试的代码
select name, color, (count(color)*100.0/count(*)) as 'perc'
from mytable
group by name, color;
答案 0 :(得分:1)
您需要获取每种颜色的总数才能获得百分比。这需要加入另一个值。我认为以下内容适用于Access:
select nc.name, nc.color, nc.cnt * 100 / n.cnt & '%'
from (select name, color, count(*) as cnt
from mytable as t
group by name, color
) as nc inner join
(select name, count(*) as cnt
from mytable as t
group by name
) as n
on nc.name = n.name;