简体   繁体   English

Sql表连接查询

[英]Sql Table join query

I have 3 tables in sql我在 sql 中有 3 个表

  1. ProductMaster with column ProductName带有 ProductName 列的 ProductMaster
  2. PurchaseData with column ProductName and Quantity带有 ProductName 和 Quantity 列的 PurchaseData
  3. SaleData with column ProductName and Quantity带有 ProductName 和 Quantity 列的 SaleData

Please guide me to write query for table join to get the result as under请指导我编写表连接查询以获得如下结果

PRODUCT1   10    5     5
PRODUCT2   10    0     10
PRODUCT3   10    5     5

Try to start with something like this:尝试从这样的事情开始:

SELECT [ProductMaster].[ProductName]
    ,[PurchaseData].[Quantity]  AS [PurchasedQuantity]
    ,[SaleData].[Quantity]      AS [SoldQuantity]
    ,[PurchaseData].[Quantity] 
        - [SaleData].[Quantity] AS [ClosingStock]
  FROM [ProductMaster]
    LEFT OUTER JOIN [PurchaseData]
        ON [ProductMaster].[ProductName] = [PurchaseData].[ProductName]
    LEFT OUTER JOIN [SaleData]
        ON [ProductMaster].[ProductName] = [SaleData].[ProductName]

The idea is to have the master table and join the two dependent tables to the master with an INNER JOIN on the ProductName field.这个想法是拥有主表并在 ProductName 字段上使用 INNER JOIN 将两个从属表连接到主表。

You don't need anymore ProductMaster Table, because all information you need are in PURCHASEDATA and SALEDATA您不再需要 ProductMaster 表,因为您需要的所有信息都在 PURCHASEDATA 和 SALEDATA 中

SELECT P.[ProductName] as ProductName, P.PurchaseQty, S.SalteQTY, P.purchaseQTY-S.SalteQTY as ClosingQty

  FROM [PURCHASEDATA] P LEFT OUTER JOIN [SALEDATA] S ON P.ProductName=S.ProductName

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

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