发生重复值尝试获取产品的上一个事务时

时间:2016-09-25 11:16:10

标签: sql-server sql-server-2008 sql-server-2012

如何避免重复值发生时尝试从表中获取产品的上一个事务。我的查询如下,我的图像就像enter image description here

SELECT
  a.branchid,
  a.TellerID,
  a.ProductID,
  a.TransactDateTime,
  a.ProductStock,
  a.ProductStockInLocalCrrncy
FROM ALX_SubInventoryCashTransfers a
INNER JOIN (
    SELECT
        branchid,
        TellerID,
        ProductID,
        MAX(TransactDateTime) datetime
    FROM ALX_SubInventoryCashTransfers
    GROUP BY branchid,
            TellerID,
            ProductID,
            TransactDateTime
) tm
  ON a.BranchID = tm.BranchID
  AND a.branchid = tm.BranchID
  AND a.TellerID = tm.TellerID
  AND a.ProductID = tm.ProductID
  AND a.TransactDateTime = tm.datetime  

3 个答案:

答案 0 :(得分:2)

通过

从组中删除TransactDateTime
from ALX_SubInventoryCashTransfers  group by
branchid,TellerID,ProductID,**TransactDateTime**) tm

您可以尝试此查询

SELECT
  a.branchid,
  a.TellerID,
  a.ProductID,
  a.TransactDateTime,
  a.ProductStock,
  a.ProductStockInLocalCrrncy
FROM ALX_SubInventoryCashTransfers a
INNER JOIN (SELECT
  branchid,
  TellerID,
  ProductID,
  MAX(TransactDateTime) as MaxDate
FROM ALX_SubInventoryCashTransfers
GROUP BY branchid,
         TellerID,
         ProductID) tm
  ON a.BranchID = tm.BranchID
  AND a.branchid = tm.BranchID
  AND a.TellerID = tm.TellerID
  AND a.ProductID = tm.ProductID
  AND a.TransactDateTime = tm.MaxDate

答案 1 :(得分:1)

可能是这样的:

with cte as (
    select
        rn = row_number() over ( partition by a.ProductID order by a.TransactDateTime desc),
        a.branchid, a.TellerID, a.ProductID, a.TransactDateTime, a.ProductStock, a.ProductStockInLocalCrrncy 
    from
        ALX_SubInventoryCashTransfers a
)
select
    a.branchid, a.TellerID, a.ProductID, a.TransactDateTime, a.ProductStock, a.ProductStockInLocalCrrncy 
from
    cte a
where
    ( a.rn = 1 )

答案 2 :(得分:1)

如果我的问题正确无误,那么您希望每个日期的日期时间最长。请尝试以下查询:

SELECT
  a.branchid,
  a.TellerID,
  a.ProductID,
  a.TransactDateTime,
  a.ProductStock,
  a.ProductStockInLocalCrrncy
FROM ALX_SubInventoryCashTransfers a
INNER JOIN (
    SELECT
        branchid,
        TellerID,
        ProductID,
        MAX(TransactDateTime) datetime
    FROM ALX_SubInventoryCashTransfers
    GROUP BY branchid,
            TellerID,
            ProductID,
            CAST(TransactDateTime AS DATE)
) tm
  ON a.BranchID = tm.BranchID
  AND a.branchid = tm.BranchID
  AND a.TellerID = tm.TellerID
  AND a.ProductID = tm.ProductID
  AND a.TransactDateTime = tm.datetime