2016-09-25 48 views
0

如何避免重复值出现当尝试从表中提取产品的最后一笔交易时。我的查询,如下所示我的形象就像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 
+0

您能告诉我们包含重复项的实际输出吗?您包含的屏幕截图显示了多个'datetime'值,这是您的查询所不可能的,因为您将限制为某个表中具有最大值的记录。 –

+1

尝试从group by子句中删除TransactDateTime字段。 –

+0

@ tim,它是重复的。我只需要一个日期一个产品价值。你可以看到在图片产品ID 2重复两次在同一个说,我只需要它在一天中只有一次 –

回答

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 
+0

我需要日期根据我需要显示的日期(每个产品的最后一个值应显示在每一天) –

+0

我在说只能从组中删除..您可以使用子查询中的maxdate –

+0

您可以尝试更新后的查询.. –

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) 
+0

它不显示正确与cte它将像明智的显示 –

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 
相关问题