I have a query that returns results.
    declare @value varchar(500) = 1
    SELECT cnb.ndc_id
        ,cnb.contract_num_val
        ,cnb.quote_price
        ,CONVERT(VARCHAR(10), cnb.eff_dt, 101) AS 'eff_dt'
        ,cnb.discount_pct
        ,cnb.rebate_pct
        ,cnb.award_type
        ,cnb.contract_ndc_brg_id
        ,(
            SELECT SUBSTRING((
                        SELECT ',' + gm.item_name AS [text()]
                        FROM GM_PROGRAM gm
                        JOIN [CONTRACT_ATTR] ca ON ca.[ATTR_VAL] = gm.Item_Id
                        WHERE field_id = 239
                            AND ca.item_id = (
                                SELECT item_id
                                FROM [CONTRACT_ATTR]
                                WHERE attr_val = cnb.contract_num_val
                                    AND field_id = 413
                                )
                        FOR XML PATH('')
                        ), 2, 1000)
            ) AS 'programs'
    FROM [ndc_attr] ndc
    INNER JOIN contract_ndc_brg cnb ON ndc.attr_val = cnb.ndc_id
    WHERE ndc.field_id = 69
I am trying to add a filter where for each unique contract_num_val it will only return the one with the highest date.
First I tried to add MAX() around CONVERT(VARCHAR(10), cnb.eff_dt, 101) and then add a group by clause. But it wouldn't run unless I added everything to group by then it just returned the same results.
Then looking here I tried to make a simpler select that I could use to get back the keys I need to filter. Based on this: SQL Select only rows with Max Value on a Column
This once again doesn't run:
select contract_ndc_brg_id, max(eff_dt) from contract_ndc_brg group by contract_num_val
I have to add contract_ndc_brg_id to the group by then it jusyt returns everything.
What am I doing wrong and how do I fix it?

 
     
    