2016-09-25 46 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 
相關問題