Sql 为唯一键选择最大日期行
我有一个select语句Sql 为唯一键选择最大日期行,sql,sql-server,Sql,Sql Server,我有一个select语句 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 ite
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
)
请注意,有两行具有相同的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
))
我发现它的问题是,它返回任何行的最大日期
我怎样才能纠正我做错了什么?是你的朋友:
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
你试过用
分组方式吗?@Sami你能详细说明一下吗?我得到:Msg 156,15级,状态1,第7行关键字“结束”附近的语法不正确。Msg 102,15级,状态1,第14行“')”附近语法不正确。修复了打字错误。从与eff_dt在同一条线上开始