0

我正在尝试查询以告诉我数据集中男性和女性的百分比(我之前提出的问题的扩展)。查询仅来自一张表。

declare @totalPop int;
declare @totalmales int;
declare @totalFemales int;
declare @percentMales float;
declare @percentFemales float;
set @totalpop =(select count(*) from myTable)
set @totalmales =(select count(*) from myTable where (sex='m'))
set @totalfemales =(select count(*) from myTable where (sex='f'))
set @percentMales=@totalMales/totalPop
set @percenFemales =@totalFemales/totalPop

select sex, count(sex), @totalPop, @totalMales, @totalFemales

我知道目前这行不通,但我不知道如何在一行上除以 totalMales,在下一行除以 totalFemales

4

2 回答 2

1
SELECT 
   DISTINCT Sex,
   @totalpop as 'TotalPopulation',
   CASE Sex
        WHEN 'm' THEN @TotalMales
        WHEN 'f' then @TotalFemales
        ELSE 'WTF?' END
   as 'SexCount'
   ...
FROM 
   MYTable

您可以使用 aCASE根据sex值选择显示的数字。

于 2012-05-11T20:25:08.773 回答
1
CREATE TABLE myTable(id NUMBER, sex CHAR(1));

INSERT INTO myTable VALUES(1, 'm');
INSERT INTO myTable VALUES(2, 'm');
INSERT INTO myTable VALUES(3, 'f');
INSERT INTO myTable VALUES(4, 'f');
INSERT INTO myTable VALUES(5, 'f');

SELECT COUNT(DISTINCT sex) AS count_distinct_sex
      ,COUNT(*) AS totalPop
      ,SUM(CASE WHEN sex = 'm' THEN  1 ELSE 0 END) AS totalMales
      ,SUM(CASE WHEN sex = 'f' THEN  1 ELSE 0 END) AS totalFemales
  FROM myTable;

COUNT_DISTINCT_SEX TOTALPOP TOTALMALES TOTALFEMALES
------------------ -------- ---------- ------------
                 2        5          2            3 
于 2012-05-11T20:59:07.113 回答