0

我想计算三个不同等级 A、B、C 的百分比

1 product have  A grade 
5 products have B grade 
3 products gave C grade 

SQL - 此查询返回 3 行

SELECT count(*) FROM table1 WHERE pid = '480' AND grade IN 
  ( SELECT DISTINCT grade FROM table1 ) 
  GROUP BY grade

  ------------------------
   CCA_ST2      count(*)
  ------------------------
     A            1 
     B            5
     C            3
 ------------------------

我如何计算百分比?

   (  SELECT count(*) FROM table1 WHERE pid = '480' AND grade IN 
      ( SELECT DISTINCT grade FROM table1 ) 
      GROUP BY grade
   ) 
   DIVIDE BY 
   ( SELECT COUNT(*) FROM table1 WHERE pid = '480' ) * 100

我试过这个查询

SELECT grade,
( SELECT count(*) FROM table1 WHERE pid = '480' AND grade IN 
  ( SELECT DISTINCT grade FROM table1 ) 
  GROUP BY grade
) 
/ 
( SELECT count(*) FROM table1 WHERE pid = '480' ) 
* 100 
AS score 
FROM table1 GROUP BY grade

我得到了这个错误。我该如何解决这个问题

subquery returns more than one row 

我真的不想为此创建程序,我知道这可以通过查询来完成。但是我今天感觉很懒。

4

1 回答 1

4

您不能从所有组中获取计数并将它们除以总计数,您必须将每个计数除以总计数:

SELECT
  grade,
  100 * count(*) / (SELECT count(*) FROM table1 WHERE pid = '480') AS score 
FROM table1
WHERE pid = '480'
GROUP BY grade
ORDER BY grade
于 2012-12-16T18:26:28.990 回答