t-sqlssrs-2014

Performing Count() and Avg() within a Case statement


I am using this CASE statement to show a total count of visits and average length of visit grouped by age groups:

    CASE WHEN AgeCalcSort = 0 AND  AgeCalcSort <= 1 then (
        Count(VisitID),
        AVG(DATEDIFF(dd,StartDate,EndDate ))
        )
    WHEN AgeCalcSort >= 2 AND  AgeCalcSort <= 17 then (
                Count(VisitID),
        AVG(DATEDIFF(dd,StartDate,EndDate ))
        )
    WHEN AgeCalcSort >= 18 AND  AgeCalcSort <= 64 then (
                Count(VisitID),
        AVG(DATEDIFF(dd,StartDate,EndDate ))
        )
    WHEN AgeCalcSort >= 65 then (
                Count(VisitID),
        AVG(DATEDIFF(dd,StartDate,EndDate ))
        )
    END,

The result should look like this:

Age 1 Count  Age 1 Avg LOS      Age 2 Count  Age 1 Avg LOS      Age 3 Count  Age 3 Avg LOS      Age 4 Count     Age 4 Avg LOS
5           5.3                 18          9.2                 20              12              0               0   

Can anyone adivse what am I doing wrong, or a better way to achieve the end result? Thanks In advance.


Solution

  • You have mentioned 2 points:

    1) Can anyone adivse what am I doing wrong

    2) a better way to achieve the end result

    Query explanation