局部变量数学显示奇怪的行为

时间:2012-05-11 20:10:33

标签: sql

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

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

2 个答案:

答案 0 :(得分:1)

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

您可以使用CASE选择您显示的号码,具体取决于sex值。

答案 1 :(得分: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