0

我有类别组和种族组,我需要赖特查询报告,看起来像这样在此处输入图像描述

现在我有可以按客户 ID 和种族计算的查询。然而,他的诡计也是客户表有西班牙裔字段(位 0 假 1 真)。客户可以有任何种族,但同时他/她可以是西班牙裔。我现在的查询可以计算客户,但对于西班牙裔,它只是列出计数而不是按种族划分

select ethnicity, COUNT (c.EthnCode) as '(A) tottal Numbers of participamts by Rase', 
(select COUNT (Hispanic) from clients c JOIN ethnicity e
ON c.EthnCode = e.EthnCode
where c.EthnCode in ('N','A','B','P','W','NW','AW','BW','BN') and Hispanic =1 )as '(B)Number of Hispanic or Latino Participants Reported in Column A by Race'
from  Clients c
JOIN ethnicity e
ON c.EthnCode = e.EthnCode
where c.EthnCode in ('N','A','B','P','W','NW','AW','BW','BN')
group by ethnicity

此外,如果某些种族没有参与者,它只是没有在结果中显示,但我需要为该种族显示 0。这是我的查询结果 在此处输入图像描述

如您所见,西班牙裔没有按类别划分。需要帮助试图解决这个问题第二天仍然没有任何成功

4

1 回答 1

2

试试这个:

select ethnicity, COUNT (c.EthnCode) as '(A) tottal Numbers of participamts by Rase', 
sum(case when Hispanic=1 then 1 else 0 end) as '(B)Number of Hispanic or Latino Participants Reported in Column A by Race'
from  Ethnicity E
LEFT JOIN Clients C
ON c.EthnCode = e.EthnCode
where e.EthnCode in ('N','A','B','P','W','NW','AW','BW','BN')
group by ethnicity

SUM(CASE...) 用作实际计数中的一种“子计数”。

更新

要将所有其他代码归为“其他倍数”类别,请执行以下操作:

select 
    case 
    when e.EthnCode in ('N','A','B','P','W','NW','AW','BW','BN') then ethnicity
    else 'Other Multiples' 
    end as ethnicity, 
    COUNT (c.EthnCode) as '(A) tottal Numbers of participamts by Rase', 
    sum(case when Hispanic=1 then 1 else 0 end) as '(B)Number of Hispanic or Latino Participants Reported in Column A by Race'
from  Ethnicity E
LEFT JOIN Clients C
ON c.EthnCode = e.EthnCode
group by case 
    when e.EthnCode in ('N','A','B','P','W','NW','AW','BW','BN') then ethnicity
    else 'Other Multiples' 
    end

这假设 Ethnicity 中所有不在硬编码语句中的 ethncode 都是倍数。

于 2013-02-25T00:10:09.457 回答