过滤列中具有相同值但不同的最大日期

时间:2017-06-09 16:37:22

标签: sql sql-server

我有一个返回结果的查询。

    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

enter image description here

我正在尝试添加一个过滤器,对于每个唯一的contract_num_val,它只返回具有最高日期的过滤器。

首先,我尝试在MAX()周围添加CONVERT(VARCHAR(10), cnb.eff_dt, 101),然后添加group by子句。但它不会运行,除非我将所有内容添加到组中,然后它返回相同的结果。

然后看这里我尝试做一个更简单的选择,我可以用它来取回我需要过滤的键。基于此:SQL Select only rows with Max Value on a Column

这再次没有运行:

select contract_ndc_brg_id, max(eff_dt) from contract_ndc_brg group by contract_num_val

我必须将contract_ndc_brg_id添加到该组,然后jusyt将返回所有内容。

我做错了什么以及如何解决?

2 个答案:

答案 0 :(得分:3)

添加此内连接

inner join
(select contract_num_val, max(eff_dt) dt 
from  contract_ndc_brg 
group by contract_num_val) cnb2 on cnb2.dt = cnb.eff_dt and cnb2.contract_num_val =cnb.contract_num_val

答案 1 :(得分:3)

使用cross apply()

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
     inner 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
  cross apply (
    select top 1 *
    from contract_ndc_brg i 
    where ndc.attr_val = i.ndc_id
    order by i.eff_dt desc
    ) cnb
where ndc.field_id = 69