2014-12-02 71 views
0

我有一個表像下面:如何使用sql查詢計算比率?

ID Name Department Gender 
1 Crib  MA  MALE 
2 Lucy  Bsc  FEMALE 
3 Phil  Bcom  MALE 
4 Ane  MA  FEMALE 

我有1000行這樣的記錄。我想從所有學生的性別列(男性&女性)中找到比率。

我需要一個查詢來執行此操作。

+1

你能告訴我們你試圖寫該問題的一些疑問? – 2014-12-02 15:44:23

+1

您正在使用哪些DBMS?你標記了sql server,mysql和oracle。 – 2014-12-02 15:45:00

回答

0

如何

select gender, count(*) 
    from table 
group by gender 

那麼它很簡單,你自己計算的比值。

+1

那要求服務器爲我做這件事? – Dror 2016-08-22 14:43:42

0

這應該給你實際比率,並且應該在MySQL和SQL Server中很少或沒有修改。您可能需要稍微修改演員陳述 - 我的MySQL很生疏,我認爲它可能會稍有不同。

SELECT 
    (CAST((SELECT COUNT(*) FROM tblName WHERE Gender='MALE') AS FLOAT)/
    CAST((SELECT COUNT(*) FROM tblName WHERE Gender='FEMALE') AS FLOAT)) 
    AS ratioMaleFemale; 
0

你八九不離十:

select (select count(*) 
      from table where gender='MALE')/count(*)*100 as percentage_male, 
     (select count(*) 
      from table where gender='FEMALE')/count(*)*100 as percentage_female 
from table; 
7

SQL Fiddle

MySQL的32年5月5日架構設置

CREATE TABLE table1 
    (`ID` int, `Name` varchar(4), `Department` varchar(4), `Gender` varchar(6)) 
; 

INSERT INTO table1 
    (`ID`, `Name`, `Department`, `Gender`) 
VALUES 
    (1, 'Crib', 'MA', 'MALE'), 
    (2, 'Lucy', 'Bsc', 'FEMALE'), 
    (3, 'Phil', 'Bcom', 'MALE'), 
    (4, 'Ane', 'MA', 'FEMALE') 
; 

查詢1

SELECT sum(case when `Gender` = 'MALE' then 1 else 0 end)/count(*) as male_ratio, 
     sum(case when `Gender` = 'FEMALE' then 1 else 0 end)/count(*) as female_ratio 
FROM table1 

Results

| MALE_RATIO | FEMALE_RATIO | 
|------------|--------------| 
|  0.5 |   0.5 | 
3

嘗試是這樣的

select sum(case when gender = 'MALE' then 1 else 0 end)/count(*) * 100 as perc_male, 
sum(case when gender = 'FEMALE' then 1 else 0 end)/count(*) * 100 as perc_female 
from students