依次列出了两个表,但它们如何链接?

时间:2019-09-19 02:05:37

标签: sql

此查询用于选择currentstock

我认为

(SELECT ItemName, SUM(Quantity) AS t1 
 FROM INVENTORYINDETAIL 
 WHERE TransType = 'PROC' 
   AND TransDate <= @TransDate 
   AND FacilityCode = @FacilityCode   
 GROUP BY ItemName)

是一个表,但紧随其后还有另一个表INVENTORYINDETAIL

这两个表是按顺序列出的,所以我不明白它们是如何链接的。

您能解释每个查询吗?

DECLARE @TransDate VARCHAR(10),
        @FacilityCode VARCHAR(5)

SET @TransDate = '2019-09-19'
SET @FacilityCode = '10'

SELECT 
    INVENTORYINDETAIL.ItemName, (t1 - t2) AS CurrentStock 
FROM
    (SELECT ItemName, SUM(Quantity) AS t1 
     FROM INVENTORYINDETAIL 
     WHERE TransType = 'PROC' 
       AND TransDate <= @TransDate 
       AND FacilityCode = @FacilityCode 
    GROUP BY ItemName) INVENTORYINDETAIL 
LEFT JOIN 
    (SELECT ItemName, SUM(Quantity) AS t2 
     FROM INVENTORYOUTDETAIL 
     WHERE OutType = 'PROC' 
     GROUP BY ItemName) INVENTORYOUTDETAIL ON INVENTORYINDETAIL.ItemName = INVENTORYOUTDETAIL.ItemName

1 个答案:

答案 0 :(得分:1)

这里只有一个查询,它使用两个子查询。我已经使用缩进功能编辑了查询,使其更加明显。

基本上,您可以创建子查询,然后将其视为表。所以查询的一部分:

from (
  SELECT ItemName,SUM(Quantity) as t1 
  from INVENTORYINDETAIL 
  WHERE TransType = 'PROC' and TransDate <= @TransDate and FacilityCode = @FacilityCode 
  group by ItemName
) INVENTORYINDETAIL 

INVENTORYINDETAIL表上运行查询,然后创建INVENTORYINDETAIL的别名(可以是任何名称),而第二部分

LEFT JOIN (
  SELECT ItemName,SUM(Quantity) as t2 
  from INVENTORYOUTDETAIL 
  WHERE OutType = 'PROC' 
  group by ItemName
) INVENTORYOUTDETAIL on INVENTORYINDETAIL.ItemName = INVENTORYOUTDETAIL.ItemName

INVENTORYOUTDETAIL执行类似的分组查询,然后将其结果与第一个查询合并。

这种类型的查询通常用于无法在表之间进行任何直接联接的地方,因为这将导致多对多联接。