gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:24:55 24 4
gpt4 key购买 nike

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

    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,它将只返回日期最长的那个。

首先,我尝试在 CONVERT(VARCHAR(10), cnb.eff_dt, 101) 周围添加 MAX(),然后添加一个 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 添加到组中,然后它会返回所有内容。

我做错了什么,我该如何解决?

最佳答案

添加这个内连接

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

关于sql - 过滤列中具有相同值但最大日期不同的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44462828/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com