2013-02-24 16 views
0

我有類別和種族的組羣,我需要的報告,該報告將看起來像這樣enter image description here查詢與數以羣

現在我有查詢,可以通過客戶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 

而且把它如果某些種族沒有perticipiants它只是沒有顯示結果,但我需要顯示爲0那種族。 這裏是我的查詢結果 enter image description here

正如你可以看到西班牙裔沒有按類別劃分。 需要幫助,試圖解決這個問題,第二天仍然沒有取得任何結果

+0

不完全確定我理解你的問題 - 你想要的輸出是什麼?第3列中的 – sgeddes 2013-02-25 00:05:50

+0

現在顯示17這是所有客戶在DB的西班牙裔狀態1的計數,它應該顯示他們被種族劃分,如報告示例 – Andrey 2013-02-25 00:11:20

回答

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 ...)作爲一種「子數」計數。

UPDATE

爲了所有其他代碼疙瘩成一個「倍數等」類別,這樣做:

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 

這裏假定種族所有ethncodes不在在你的硬編碼聲明中是多個。

+0

thanx!但是對於那些沒有任何活躍客戶的種族來說呢,就我而言,它是亞洲白人AW。根據業務規則,這條線必須在報告中,即使它們中的值是0 – Andrey 2013-02-25 00:16:33

+1

我更新了我的答案。簡短的回答是你必須離開加入種族的客戶。所以,即使沒有客戶,種族依然得到回報,其數量和金額都是0. – 2013-02-25 00:19:35

+0

真棒!也許你也幫助我在原始報告中的第14行,它也必須按類別和種族計算所有客戶,但僅限於那些不是'N','A','B','P','W ','NW','AW','BW','BN'有很多組合,他們必須被列爲一行,名稱有些像多個 – Andrey 2013-02-25 00:28:53