如何计算选择查询中每个组的百分比

时间:2015-12-23 14:42:59

标签: sql percentage

我在下面的查询中计算每个组的出现次数

SELECT ss.year, COUNT(*) 
FROM stackexchange_question seq
INNER JOIN secondary_study ss ON seq.secondary_study_code = ss.code
WHERE (seq.evaluation LIKE 'PARTIALLY' OR  seq.evaluation LIKE 'TOTALLY')
GROUP BY ss.year
ORDER BY ss.year;

下面的另一个查询计算每个组的一部分

SELECT ss.year, COUNT(*) FROM stackexchange_question seq
INNER JOIN secondary_study ss ON seq.secondary_study_code = ss.code
WHERE (seq.evaluation LIKE 'PARTIALLY' OR  seq.evaluation LIKE 'TOTALLY') AND (seq.percentile = 90)
GROUP BY ss.year
ORDER BY ss.year;

第一个查询返回:

2008|36
2009|21

第二个回归:

2008|17
2009|11

如何将第二个查询中每个组的每个计数除以第一个查询返回的计数以获得百分比?

3 个答案:

答案 0 :(得分:1)

Ue条件聚合。这是一个简单的方法:

SELECT ss.year, COUNT(*),
       AVG(CASE WHEN (seq.percentile = 90) THEN 1.0 ELSE 0.0 END) as ProportionAT90
FROM stackexchange_question seq INNER JOIN
     secondary_study ss
     ON seq.secondary_study_code = ss.code
WHERE seq.evaluation IN ('PARTIALLY', seq.evaluation LIKE 'TOTALLY')
GROUP BY ss.year
ORDER BY ss.year
ORDER BY ss.year;

答案 1 :(得分:1)

您可以将这两个查询中的where子句用作case表达式。然后计算出现次数并将其除以另一个。

SELECT ss.year, 
1.0 * 
sum(case when (seq.evaluation LIKE 'PARTIALLY' OR  seq.evaluation LIKE 'TOTALLY') 
      AND seq.percentile = 90 then 1 else 0 end)
/ sum(case when seq.evaluation LIKE 'PARTIALLY' OR seq.evaluation LIKE 'TOTALLY' then 1 else 0 end)
as pct
FROM stackexchange_question seq
INNER JOIN secondary_study ss ON seq.secondary_study_code = ss.code
GROUP BY ss.year
ORDER BY ss.year;

答案 2 :(得分:0)

select (countsTab2.cnt/countsTab1.cnt) * 100.00 as percentage,
            year
from
(SELECT ss.year, COUNT(*)  as cnt
FROM stackexchange_question seq
INNER JOIN secondary_study ss ON seq.secondary_study_code = ss.code
WHERE (seq.evaluation LIKE 'PARTIALLY' OR  seq.evaluation LIKE 'TOTALLY')
GROUP BY ss.yearORDER BY ss.year
ORDER BY ss.year) as countsTab1
inner join
(SELECT ss.year, COUNT(*)  as cnt  FROM stackexchange_question seq
INNER JOIN secondary_study ss ON seq.secondary_study_code = ss.code
WHERE (seq.evaluation LIKE 'PARTIALLY' OR  seq.evaluation LIKE 'TOTALLY') AND (seq.percentile = 90)
GROUP BY ss.year
ORDER BY ss.year) as countsTab2
on countsTab1.year = countsTab2.year