尝试从另一个具有最高日期的表中更新一列。
Table 1
示例:
PartNumber | Cost
1000 | .10
1001 | .20
Table 2
示例:
PartNumber | Cost | Date
1000 | .10 | 2017-01-01
1000 | .50 | 2017-02-01
1001 | .20 | 2017-01-01
1002 | .50 | 2017-02-02
我想用table2中的最新值更新表1,每个值为.50 ...我用来更新这个的查询工作得很好,直到我意识到我没有抓住正确的成本,因为有倍数......我现在想要获得最高版本的修订。
我的查询:
UPDATE dex_mfgx..insp_master
SET dex_mfgx..insp_master.costperpart = t2.sct_cst_tot
FROM dex_mfgx..insp_master AS t1
INNER JOIN qad_repl..sct_det_sql AS t2
ON t1.partnum = t2.sct_part
WHERE t1.partnum = t2.sct_part and t2.sct_cst_date = MAX(t2.sct_cst_date) ;
我的错误:
Msg 147, Level 15, State 1, Line 6
An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.
HAVING或GROUPING没有太多运气,虽然我没有多用它们。
任何想法都有帮助吗?
答案 0 :(得分:3)
我想我明白你现在要解决的问题。感谢Lamak让我直截了当,因为我最初离开了基地。
我想这就是你想要的东西。
with TotalCosts as
(
SELECT t2.sct_cst_tot
, t1.partnum
, RowNum = ROW_NUMBER() over(partition by t1.partnun order by t2.sct_cst_date desc)
FROM dex_mfgx..insp_master AS t1
INNER JOIN qad_repl..sct_det_sql AS t2 ON t1.partnum = t2.sct_part
)
update t1
set costperpart = tc.sct_cst_tot
from dex_mfgx..insp_master AS t1
join TotalCosts tc on tc.partnum = t1.partnum
where tc.RowNum = 1