选择唯一键的最大日期行

时间:2017-06-13 23:08:58

标签: sql sql-server

我有一个选择陈述。

            SELECT x.ndc_id
        ,z.attr_val AS trade_name
        ,x.quote_price
        ,x.eff_dt FROM contract_ndc_brg x 
        LEFT JOIN ndc_attr AS z ON z.field_id = 150
        where contract_num_val = (
            SELECT item_name
            FROM [contract]
            WHERE item_id = 184 
            )

enter image description here

请注意,有两行具有相同的ndc_id。我想要这些结果,但每个ndc_id只有一个结果eff_dt

我尝试添加到where子句:

            SELECT  x.ndc_id
        ,z.attr_val AS trade_name
        ,x.quote_price
        ,x.eff_dt FROM contract_ndc_brg x 
        LEFT JOIN ndc_attr AS z ON z.field_id = 150
        where contract_num_val = (
            SELECT item_name
            FROM [contract]
            WHERE item_id = 184
            ) and  x.eff_dt = (select max(eff_dt) from contract_ndc_brg where contract_num_val = (
            SELECT item_name
            FROM [contract]
            WHERE item_id = 184
            ))

我发现问题在于它返回任何行的最大日期。

如何解决我的错误?

1 个答案:

答案 0 :(得分:1)

ROW_NUMBER()是你的朋友:

with q as
(
      SELECT x.ndc_id
        ,z.attr_val AS trade_name
        ,x.quote_price
        ,x.eff_dt
        ,row_number() over (partition by nc_id order by eff_dt desc) rn
        FROM contract_ndc_brg x
        LEFT JOIN ndc_attr AS z ON z.field_id = 150
        where contract_num_val = (
            SELECT item_name
            FROM [contract]
            WHERE item_id = 184 
            )
)
select nc_id, trade_name, quote_price, eff_dt
from q
where rn = 1