我厌倦了SQL并尝试了几个小时,有人能告诉我怎么写这个吗?
我有一个名为动物的表,列Species
和Age
。
例如:
+-----------------------+
| Species | Age |
+-----------------------+
| Dog | 3 |
|------------|----------|
| Dog | 18 |
|------------|----------|
| Cat | 3 |
|------------|----------|
| Dog | 20 |
+-----------------------+
我想弄清楚,对于每个物种,3岁以上的所有动物中有多少百分比是该物种,并且所有3岁以下动物的百分比都是该物种。
所以会告诉我类似的东西:
狗4.5%(意味着所有3岁以下动物的4.5%是狗)23%(意味着所有3岁以下动物的23%是狗)
Cat 7.8%12%
等等
非常感谢
答案 0 :(得分:3)
尝试此查询:
SELECT
Species,
100.0 * COUNT(CASE WHEN Age = 3 THEN 1 END) /
(SELECT COUNT(*) FROM yourTable WHERE Age = 3) AS 3_pct,
100.0 * COUNT(CASE WHEN Age <> 3 THEN 1 END) /
(SELECT COUNT(*) FROM yourTable WHERE Age <> 3) AS not_3_pct,
FROM yourTable
GROUP BY Species;
分子计算特定物种中3岁时的动物数量:
COUNT(CASE WHEN Age = 3 THEN 1 END)
分母计算3岁时所有动物的数量:
(SELECT COUNT(*) FROM yourTable WHERE Age = 3)
答案 1 :(得分:0)
获得所有狗和3岁的动物的百分比:
declare @p int;
select @p = (100.0 * COUNT(a.Species) / (select COUNT(*) from Animals)) from Animals a
where a.Age = 3 and a.Species = 'dog'
group by a.Species
print CONVERT(NVARCHAR, @p) + '% of animals age 3 are dogs';
答案 2 :(得分:0)
SELECT name,age, count(age) as event_count, count(age) * 100.0 / (select count(*) from animal) as event_percent FROM animal group by age