我正在尝试从另一台服务器中选择信息,并通过打开的查询将其插入到表格中......这是我到目前为止所处的位置:
INSERT INTO smallprojects..PhyInv_310QADLockedDet (MasterRecid, location, partnum, qty)
SELECT @@IDENTITY, ld_loc, ld_part, ld_qty_oh
FROM OPENQUERY(LANSRHQAD, 'SELECT ld_loc,ld_part,ld_qty_oh FROM PUB.ld_det as a left outer join PUB.pt_mstr as b on a.ld_part = b.pt_part where pt_status <> ''OB'' and ld_part not like ''S%'' and ld_part not like ''N%'' and ld_loc = ''310'' ')
但如果PUB.ld_det具有该部分的多个条目,则会插入多个部件号,类似于以下示例:
这是数据(PUB.ld_det):
Part | Date | Qty
-------------------
1000 | 10-02 | 0
1000 | 10-03 | 2
1001 | 10-2 | 0
1001 | 10-2 | 2
我希望我的结果是插入表格中:
Part | Qty
-------------------
1000 | 2
1001 | 2
目前它正在返回:
Part | Qty
-----------
1000 | 0
1000 | 2
1001 | 0
1001 | 2
所以当我回去更新这个表时,我不得不希望它找到正确的行。
如何避免引入倍数并仅将其带入最高日期?打开的查询事情让我非常困扰
答案 0 :(得分:1)
这是一个简单的方法,你想要每个部分有一行:
INSERT INTO smallprojects..PhyInv_310QADLockedDet (MasterRecid, location, partnum, qty)
SELECT TOP (1) WITH TIES @@IDENTITY, ld_loc, ld_part, ld_qty_oh
FROM OPENQUERY(LANSRHQAD, 'SELECT ld_loc,ld_part,ld_qty_oh FROM PUB.ld_det as a left outer join PUB.pt_mstr as b on a.ld_part = b.pt_part where pt_status <> ''OB'' and ld_part not like ''S%'' and ld_part not like ''N%'' and ld_loc = ''310'' ')
ORDER BY ROW_NUMBER() OVER (PARTITION BY ld_part ORDER BY ld_qty_oh DESC);
如果您想要有重复项,请使用RANK()
。