我有一些类别和种族群体,我需要对报告进行查询,看起来像这样
现在我有查询可以按客户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。 这是我查询的结果
如你所见,西班牙裔不按类别划分。 需要帮助试图解决这个问题第二天仍然没有任何成功
答案 0 :(得分: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
这假设种族中不在您的硬编码语句中的所有民族代码都是倍数。