Mysql

如何在下面的查詢中獲得百分比?

  • April 20, 2020

一個小變化:每年報告當年只有女性演員的電影的百分比,以及當年製作的電影總數。

SELECT Year,
      COUNT(*),
      (COUNT(*)*100/(count(Movie.mid)*1.0))
FROM Movie
WHERE TRIM(MID) IN (SELECT TRIM(MID)
                   FROM M_Cast
                   WHERE TRIM(PID) IN (SELECT TRIM(PID)
                                       FROM PERSON
                                       WHERE Gender ='Female'
                                      )
                  )
GROUP BY Movie.Year
ORDER BY COUNT(*) DESC

我應該改變什麼以獲得正確的百分比?

我將使用適合該目的的新數據庫設計來處理它。 數據庫設計

所以 Movie 實體與 Person 實體有一個:m 關係。一個人出演了很多電影,而一部電影的演員陣容中有很多人。電影實體有一個年份列,人物實體有一個性別列。

因此,在此處的 SQLFiddle中創建此數據庫。通過查詢創建兩個表,如下所示。

DROP TABLE IF EXISTS temp1;
DROP TABLE IF EXISTS temp2;
CREATE TABLE temp1 (
 SELECT COUNT(Pname) AS pcount, 
   Pname, 
   YEAR 
 FROM Movie m, 
   Person p, 
   M_Cast MC 
 WHERE  gender="Female" 
 AND m.mid=mc.mid 
 AND p.pid=mc.pid  
 GROUP BY YEAR,pname
);

create table temp2 
select Year, sum(pcount) as sumyear 
from temp1 
group by Year;

然後查詢這兩個臨時表:

select
 t1.pname,
 t1.year,
 t1.pcount as MoviesByPerson,
 t2.sumyear MoviesInYear, 
 t1.pcount*100/t2.sumyear as percentage 
from temp1 t1, temp2 t2 
where t1.year=t2.year 

您可以執行 SQL Fiddle 程式碼段並查看結果。

引用自:https://dba.stackexchange.com/questions/265331