Hi @Sherlan Emmanuel Burgonia
(1) As experts answered, the alias such as "Indicator A" was added in SELECT clause which is Step 5. Therefore, you cannot use these aliases in Step 3 (Group By) or Step 4 (Having).
Solution 1: Use full expression instead of alias in HAVING clause. Like this:
HAVING (AVG(CAST(C.Column6 AS DECIMAL(10,4))) > 0)
OR (AVG(CAST(C.Column6 AS DECIMAL(10,4))) = 0 AND AVG(CAST(C.Column7 AS DECIMAL(10,4))) = 0)
Solution 2: Use subquery or CTE. Refer to Erland's answer.
(2) Regarding the GROUP BY clause, you have A.Column5 in SELECT clause, while it is not contained in either an aggregate function or the GROUP BY clause.
Try this query:
;WITH CTE AS
( SELECT A.ID,A.Column1,A.Column2,B.Column3,B.Column4,
CASE WHEN A.Column5 IS NULL THEN 'Yes' ELSE 'No' END AS Checker,
CAST(C.Column6 AS DECIMAL(10,4)) AS Column6,
CAST(C.Column7 AS DECIMAL(10,4)) AS Column7
FROM TABLE_A A JOIN TABLE_B B ON A.ID = B.ID
JOIN TABLE_C C ON A.ID = C.ID
)
SELECT ID,Column1,Column2,Column3,Column4,Checker,
AVG(Column6) AS "Indicator A",
AVG(Column7) AS "Indicator B"
FROM CTE
GROUP BY ID,Column1,Column2,Column3,Column4,Checker
HAVING (AVG(Column6) > 0) OR (AVG(Column6) = 0 AND AVG(Column7) = 0)
Best regards,
LiHong
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.