2017-02-14 64 views
1

所以我想要做的就是顯示每個家庭中有多少個年齡在5-18歲之間的孩子。我使用SQL SERVER。在VIEW上計算的列上執行COUNT()

我寫來獲得家族成員中世紀的看法是

CREATE VIEW VActiveMembers 
AS 
    SELECT 
     TM.intMemberID AS intMemberID, 
     TM.strFirstName AS strFirstName, 
     TM.strLastName AS strLastName, 
     TM.strEmailAddress AS strEmailAddress, 
     TM.dtmDateOfBirth AS dtmDateOfBirth, 
     FLOOR(DATEDIFF(DAY, dtmDateOfBirth, GETDATE())/365.25) AS intMemberAge 
    FROM 
     TMembers AS TM 
    WHERE 
     TM.intStatusFlagID = 1 

intStatusFlag = 1僅僅是一個標誌,這意味着該成員是有效的。

現在我已經嘗試了約3個小時來弄清楚這一點,但我無法弄清楚。這裏是一個不是試圖在一個家禽突擊中獲得解決方案的地方,而是試圖逐步推進它,但是我仍然沒有得到我想要的結果。

正如你所看到的,我沒有使用我計算AGE的視圖,因爲「多部分標識符不能被綁定」我已經看到了這個錯誤,但我無法讓它在這裏消失案件。理想情況下,我想伯爵一遍重新計算年齡

CREATE VIEW VActiveFamilyMembersK12Count 
AS 
    SELECT 
     TF.intParishFamilyID, 
     COUNT(DATEDIFF(DAY, dtmDateOfBirth, GETDATE())/365) AS intMemberAgeCount 
    FROM 
     TFamilies AS TF 
    INNER JOIN 
     TFamilyMembers AS TFM 
    INNER JOIN 
     VActiveMembers AS vAM ON (TFM.intMemberID = vAM.intMemberID) 
     ON (TFM.intParishFamilyID = TF.intParishFamilyID) 
    WHERE 
     TF.intStatusFlagID = 1 
    GROUP BY 
     TF.intParishFamilyID 

我想用年齡計算正好看到剛剛得到一個數。如果我能得到成員的正確數量上的VIEW來執行,而不是在一個家庭中,那麼我可以開始建立一個計算某個年齡的成員的計數。我得到的結果是2,但每個家庭都有3名成員。

我尋找的結果是這樣的

Family_ID |  K12Count 
----------------------------- 
1001   |  2 
1002   |  0 
1003   |  1 
1004   |  0 

這裏的資源列表我擡頭試圖弄清楚這一點,他們也許有其實答案,我只是不明白它,但我目前處於虧損狀態。

SQL Select Count from below a certain age

How to get count of people based on age groups using SQL query in Oracle database?

Count number of user in a certain age's range base on date of birth

Conditional Count on a field

http://timmurphy.org/2010/10/10/conditional-count-in-sql/

在先進的感謝!

*編輯*

CREATE VIEW VActiveFamilyMembersK12Count 
AS 
SELECT 
TF.intParishFamilyID, 
SUM(CASE WHEN intMemberAge >= 5 AND intMemberAge <= 18 THEN 1 ELSE 0 END) AS intK12Count 
FROM 
TFamilies AS TF 
    INNER JOIN TFamilyMembers AS TFM 
     INNER JOIN VActiveMembers AS vAM 
     ON (TFM.intMemberID = vAM.intMemberID) 
    ON (TFM.intParishFamilyID = TF.intParishFamilyID) 

WHERE 
TF. intStatusFlagID = 1 

GROUP BY 
TF.intParishFamilyID 

GO 

THIS IS上述方案。

+0

您使用的是SQL Server嗎? –

+0

是的,對不起,我應該把這個問題 – user3119737

回答

0

有條件計數是要走的路。 類似於:

SELECT intParishFamilyID, 
COUNT(CASE WHEN intMemberAge >=5 and intMemberAge <=18 THEN 1 ELSE 0 END) 
FROM 
    TFamilies AS TF 
     INNER JOIN TFamilyMembers AS TFM 
      INNER JOIN VActiveMembers AS vAM 
      ON (TFM.intMemberID = vAM.intMemberID) 
     ON (TFM.intParishFamilyID = TF.intParishFamilyID) 

WHERE 
    TF. intStatusFlagID = 1 

GROUP BY 
    TF.intParishFamilyID 
+0

OR和AND區別很大。這是我輸入OR和意義AND的工作。 – user3119737