简体   繁体   English

SQL内部联接两列(是一列中的最小值)

[英]SQL Inner Join two Columns(being the minimum from the one column)

I am working on a project here where I have two tables, one with expiry dates named tracking and one with inventory data named inventoryreport. 我正在这里的一个项目中工作,这里有两个表,一个表的到期日称为tracking,另一个表的库存数据名为inventoryreport。 I need to gather the minimum expiry date from the tracking table as well as the quantity associated with it and update the inventoryreport table. 我需要从跟踪表中收集最小到期日期以及与之关联的数量,并更新清单报告表。 The unique identifier in each table is the SKU number. 每个表中的唯一标识符是SKU号。 So far this is what I have, I know it is is incomplete and I have tried min() on the tracking.expirydate I would appreciate any suggestions. 到目前为止,这是我所拥有的,我知道它是不完整的,我已经在tracking.expirydate上尝试了min(),我将不胜感激任何建议。

UPDATE InventoryReport
INNER JOIN tracking ON [InventoryReport].[SKU] = [tracking].[SKU]
SET [InventoryReport].[Expiry Date]  = [tracking].[Expiry Date], 
[InventoryReport].[Quantity] = [tracking].[Quantity];

If there exists nothing smaller than something, then it is the minimum, or in SQL: 如果不存在小于事物的东西,则为最小值,或在SQL中:

UPDATE InventoryReport AS i
INNER JOIN tracking AS t ON t.[SKU] = i.[SKU] AND NOT EXISTS(
    SELECT t2.[Expiry Date]
    FROM tracking AS t2
    WHERE t2.[SKU] = t.[SKU] AND t2.[Expiry Date] < t.[Expiry Date]
) SET i.[Expiry Date] = t.[Expiry Date], 
      i.[Quantity] = t.[Quantity]
;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM