AS the error message mentioned, if you want to select the field which is not an aggregate function, i.e., SUM, COUNT, MAX, MIN and so on, you have to include it in the GROUP BY statement.
Is there a good way to get around this? I understand the error but I don't want to group by DRG rate or wrap in an aggregate, I just want the matching DRG Rate per unique patient.
I do not know why you do not want DRG Rate in the GROUP BY. You can try this:
;WITH CTE_PATNO_DRG AS (
SELECT DISTINCT PATNO, DRG
FROM BCBS$]
),
CTE_SUM_By_PATNO AS (
SELECT PATNO, SUM(AMT) AS [AMT]
FROM BCBS$
GROUP BY PATNO
)
SELECT s.PATNO,
CASE WHEN s.AMT > 275000 THEN CAST((s.AMT-275000)*.195+d.[DRG Rate] AS varchar(20)) ELSE 'NO' END AS StopLoss,
CASE WHEN s.AMT > 275000 THEN (s.AMT-275000)*.195+DR.[DRG Rate] ELSE d.[DRG Rate] END AS ClaimTotal,
d.[DRG Rate],
d.[DRG Code] AS DRG,
FROM CTE_SUM_By_PATNO AS s
INNER JOIN CTE_PATNO_DRG AS d ON d.PATNO = s.PATNO
Please note in the first CASE statement, since (s.AMT-275000)*.195+DR.[DRG Rate] returns a decimal, you cannot use 'NO' in the ELSE. So you need to convert the decimal to varchar and then you can use 'NO' in the ELSE.