从VIEW对计算列执行COUNT()

时间:2017-02-14 20:07:22

标签: sql-server tsql count views calculated-columns

所以我想做的就是有一个视图,显示每个家庭中有多少孩子,包括5-18岁。我正在使用SQL SERVER。

我为了获得家庭成员而写的观点是

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的视图,因为“多部分标识符无法绑定”我看到了这个错误,但在这种情况下我无法让它消失。理想情况下,我希望在VIEW上执行计数,而不是重新计算年龄

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

我想通过年龄计算得到一个计数只是为了看看如果我能在一个家庭中得到正确的成员数,那么我可以开始建立这个以获得一定年龄的成员数。我得到的结果是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

这是上面的解决方案。

1 个答案:

答案 0 :(得分:1)

条件计数是要走的路。 类似的东西:

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
相关问题