【问题标题】:Creating a view and getting duplicate transactions创建视图并获取重复事务
【发布时间】:2012-12-12 03:59:13
【问题描述】:

我有以下看法:

SELECT     t.CompanyCode, t.FlatFileName, t.RecordNumber, t.Status, t.Branch, t.SalesMonthYear, t.SalesCashOrLimboCode, t.PageNumber, t.Driver, t.Truck, 
                      t.CommonProductCode, t.CashCharge, t.SpecialFunction, t.ProductCode, t.UnitOfEntry, t.TransactionBranch, t.AccountNumber, t.ReferenceNumber, t.TransactionDate, 
                      t.PercentFullOrWhenDueCode, t.Quantity, t.DeliveryAccountNumberForTankRentals, t.Amount, t.SalesTax, t.ProductCode2Amount, t.TankSerialNumber, t.SalesMonth, 
                      t.TaxCode, t.SubjectToTax, t.SalesTaxRate, t.ExiseTaxRate, t.FrankHasntDecidedWhatThisFieldIs_ProbablyCentury, t.OriginalSalesMonth, t.AutoCharge, 
                      t.ProductCode2, t.ProductCode2SpecialFunction, t.DiscountCode, t.DiscountRate, t.DiscountDays, t.Century, t.TRFRPD, t.OpenItemAmountPaid, 
                      t.OpenItemReferenceNumber, t.InvoiceFlag, t.InvoiceNumber, t.Time, t.GasQuantity, t.AnodeReading, t.Reading, t.Reason, t.InventorySerialNumber, t.SName, 
                      t.ErrorCode, t.MasterBillingBranchAccountNumber, t.LeaseOnFile, t.PuchaseOrderNumber, t.BillOfLaden, t.Latitude, t.Longitude, t.ContractGasPrice, t.Balance, 
                      t.DeliveryAccount, t.BranchAccountNumber, t.LineNumber, t.DateTimeEntered, t.UserThatEntered, t.WorkstationThatEntered, t.YearMonthDayPosted, 
                      t.HourMinutePosted, t.UserThatPosted, t.WorkstationThatPosted, t.CreditCardNumber, t.CreditCardExperationDate, t.CreditViolation, t.TransactionId, t.CorporationId, 
                      t.IsUpdated, t.IsAdded, t.ClearUpdateAndAdded, p.Description
FROM         Company.Product AS p LEFT OUTER JOIN
                      Company.[Transaction] AS t ON p.ProductCode = t.ProductCode AND p.CorporationId = t.CorporationId

我要完成的主要工作是从产品表中获取产品描述并将其添加到事务表中。它必须基于 ProductCode。

我应该只获得每笔交易一次,但我会获得每笔交易的多个副本。我知道每个公司都有产品,所以我认为是因为它看到了这些?

从这个website,它说使用左外连接:

此连接返回左表中的所有行 右表中的匹配行。如果没有列 在正确的表中匹配,它返回 NULL 值。

我没有在描述中得到空值,所以我不知道我做错了什么。

【问题讨论】:

  • 我假设您有一对多的关系,即对于一笔交易,您有很多产品。不是吗?
  • 每个 ProductCode 是否有多个 CorporationID?这可能会导致这种情况。上述查询的 LEFT OUTER JOIN 不会在描述中为您提供 NULL;它会在 Company 表的所有字段中为您提供 NULL。是这样吗?如果将 DISTINCT 添加到 SELECT 语句中,是否会更改返回的行数?如果是这样,你就有了真正的重复;否则,有些数据是不同的。

标签: tsql view outer-join


【解决方案1】:

我会改变你的桌子的顺序:

SELECT  <yourcols>
FROM   company.[transaction] AS t 
LEFT OUTER JOIN company.product AS p 
   ON t.productcode = p.productcode
   AND t.corporationid = p.corporationid 

【讨论】:

    【解决方案2】:

    您可能希望加入该产品的交易,因为每个产品都有不止一个交易。我会在您的联接中交换订单,并且我也不会在 OUTER 联接中使用,因为在您的场景中,您希望您查询的所有交易都存在 1-1(即没有没有产品的交易)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-26
      • 2011-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多