我可以声明TOP来从另一个表中提取值吗

时间:2018-06-28 17:40:30

标签: sql-server sql-server-2008-r2

我想从库存表中收集TOP差异,其中newcount <>数量。 基本上,如果我的库存数量与应有的数量不同,我想在剩余的库存中搜索缺少零件的TOP#。这带给我一个库存ID,以确保我先删除最旧的零件。 我可能有900个,所以我正在寻找一个sql命令,该命令根据库存中的差异和零件号返回来自partsmainingfifo的结果。

select 
    PartNumber, 
    Quantity, 
    NewCount, 
    diff
from Inventory
where NewCount <> Quantity

+------------+----------+----------+------+
| PartNumber | Quantity | NewCount | diff |
+------------+----------+----------+------+
|    2871451 |        1 |        0 |    1 |
|    4932615 |        6 |        1 |    5 |
+------------+----------+----------+------+


select top 1 
    id, PartNumber, 
    PartDescription, 
    Quantity, 
    TotalPrice,
    Brand, 
    Location, 
    Account
from PARTSREMAININGFIFO
where PartNumber = '2871451'


+------+------------+-------------------+----------+------------+---------+----------+----------+
|  id  | PartNumber |  PartDescription  | Quantity | TotalPrice |  Brand  | Location | Account  |
+------+------------+-------------------+----------+------------+---------+----------+----------+
| 9183 |    2871451 | AFM DEVICE GASKET |        1 |  19.815225 | CUMMINS | A1       | 6015-Z   |
+------+------------+-------------------+----------+------------+---------+----------+----------+




select top 5 
    id, 
    PartNumber, 
    PartDescription, 
    Quantity, 
    TotalPrice,
    Brand, 
    Location, 
     Account
from PARTSREMAININGFIFO
where PartNumber = '4932615'


+------+------------+-----------------+----------+------------+---------+----------+---------+
|  id  | PartNumber | PartDescription | Quantity | TotalPrice |  Brand  | Location | Account |
+------+------------+-----------------+----------+------------+---------+----------+---------+
| 3264 |    4932615 | GASKET          |        1 |   2.907144 | CUMMINS | A1       | 6015-Z  |
| 9780 |    4932615 | GASKET          |        1 |   5.053475 | CUMMINS | A1       | 6015-Z  |
| 9781 |    4932615 | GASKET          |        1 |   5.053475 | CUMMINS | A1       | 6015-Z  |
| 9782 |    4932615 | GASKET          |        1 |   5.053475 | CUMMINS | A1       | 6015-Z  |
| 9783 |    4932615 | GASKET          |        1 |   5.053475 | CUMMINS | A1       | 6015-Z  |
+------+------------+-----------------+----------+------------+---------+----------+---------+

1 个答案:

答案 0 :(得分:1)

我了解您现在想要什么,并且我认为您需要一个游标。重要提示,除非您不在乎什么行会返回,否则必须在使用FILENAME:= $(wildcard dir/txts/*/*.txt) .PHONY: build-txt build-txt: $(FILENAME) sh build-txts.sh $^ 时指定order byRead this article.

这是实现此方法的方法:

TOP