SQl按年查询结果

时间:2012-05-07 14:59:30

标签: sql count pivot case

我有一个包含以下列的Client表。

 Admit_date    Gender     Homeless   Unemployed    Deleted 
 4/2/2012      Male         Yes         Yes           0
 1/1/2011      Female       Yes         Yes           0
 12/2/2011     Male          No          No           0
 5/23/2009     Female       Yes         Yes           0
 4/3/2009      Male          No          No           0
 7/4/2010      Male         Yes         Yes           0
 9/2/2010      Male         Yes         Yes           0 

我需要显示每年每组的百分比。我认为这需要一个数据透视表:

                 2009      2010     2011    2012
 Admitted         2          2        2      1
 Male            50%       100%     50%    100%
 Female          50%         0      50%      0%
 Homeless        50%       100%     50%     100%
 Unemployed      50%       100%     50%     100% 

此查询为我提供了每年的计数:

 select year(admit_date_c) as Year_of_Admit,count((admit_date_c)) as Admitted
 from clients where deleted = '0' 
 group by year(admit_date_c)

 Year_of_Admit   Admitted
   2009             2
   2010             2
   2011             2
   2012             1

我尝试使用案例计数进行了大量的查询迭代,但无法弄清楚如何获得性别,无家可归者和失业者的计数或百分比。有了这个,我想我可以转动表格以获得我需要的显示。

1 个答案:

答案 0 :(得分:10)

我认为应该这样做:

select year(admit_date) as year_of_admit,
  sum(case when gender='Male' then 1 else 0 end)*100/count(*) as Male, 
  sum(case when gender='Female' then 1 else 0 end)*100/count(*) as Female, 
  sum(case when homeless='Yes' then 1 else 0 end)*100/count(*) as Homeless
from client
group by year(admit_date)

我不知道你是否可以拥有除男性/女性以外的值或是/否,如“未知”。在这种情况下,你必须决定,例如,10个男性,5个女性和5个未知数是否意味着50%的男性,即50%被认为是男性,或66%是男性,即66%的性别已知的人是男性。