我一直試圖重新做這個聲明,但無濟於事。現在SQL SUM和CASE和DISTINCT
SELECT b.Program AS Program,
SUM(CASE WHEN a.Gender LIKE 'M%' THEN 1 ELSE NULL END) AS Males,
SUM(CASE WHEN a.Gender LIKE 'F%' THEN 1 ELSE NULL END) AS Females,
SUM(CASE WHEN e.Activity LIKE 'Arts' THEN 1 ELSE NULL END) AS Arts,
AVG(CASE WHEN a.Gender LIKE 'M%' THEN CAST(f.Score AS DEC(10,2)) ELSE NULL END)
AS MalesAverage
FROM tblChildren a
LEFT JOIN tblInvolvement b ON b.ChildID = a.ChildID
LEFT JOIN tblActivities e ON e.ChildID = b.ChildID
LEFT JOIN tblScores f ON f.ChildID = b.ChildID
WHERE b.Place = 'Location'
AND b.Program = 'Program'
AND b.Year = '2009-10'
AND f.Assessment LIKE '%Pre%Assessment%'
AND e.StudentID = b.StudentID
GROUP BY Program
我會得到類似的結果:
Program Males Females Arts MalesAverage
---------------------------------------
Program 7 5 1 50.000000
這樣做的問題是,目前只有4男3名女,並且,當我加入tblActivites,它似乎給副本。看完後,我注意到Activities表中有12個ChildID,原因是這些Children被綁定到多個活動。我嘗試使用類似的東西:
SELECT SUM(DISTINCT CASE WHEN a.Gender LIKE 'M%' THEN 1 ELSE NULL END) AS Males
但它只是返回1下的男性列。任何幫助,將不勝感激。爲了進一步澄清,表格通過ChildID鍵合在一起,我只需要幫助確保我返回正確的信息。如果這個問題解決了,那麼我的大量這些東西將被解決。首先避免使用GROUP BY,因爲我有很多數據。
@niktrs正如下面的回答中所解釋的,仍然給出7個男性,當正確的結果應該是4. – jnewkirk
檢查表和連接之間的關係。運行沒有聚合的查詢並檢查結果是否有任何奇怪的結果。 – niktrs