2016-09-21 59 views
1

我想列出每個SKU在一個表中的條形碼,但在某些情況下,條形碼是不同的,所以我想從一個SKU一個條形碼和返回的條形碼應該是UpdateDate最新的條形碼。GROUP BY與MAX(日期)在表中與複合主鍵

實施例:

StoreID  SKU BarCode   UpdateDate 
------------------------------------------------------------- 
1   95810 28471000000  10/06/2016 04:20:00 a.m. 
1   95810 30040050033  01/03/2012 01:00:00 a.m. 
2   44320 65453102001  15/05/2010 01:00:00 a.m. 
2   44320 12343102001  01/01/2015 01:00:00 a.m. 

期望的結果應該是:

StoreID  SKU BarCode   UpdateDate 
------------------------------------------------------------- 
1   95810 28471000000  10/06/2016 04:20:00 a.m. 
2   44320 12343102001  01/01/2015 01:00:00 a.m. 

我已經使用

SELECT 
    t.SKU, r.MaxTime 
FROM 
    (SELECT 
     P.SKU, MAX(P.Fec_Movto) as MaxTime 
    FROM 
     Productos as P 
    GROUP BY 
     P.SKU) r 
INNER JOIN 
    Productos t ON t.SKU = r.SKU AND t.Fec_Movto = r.MaxTime 

嘗試,但這裏的問題是,主鍵是一個複合主鍵所以它根本不起作用。

回答

3

可能使用ROW_NUMBER像

select * from 
(select StoreID,SKU,BarCode,UpdateDate 
,row_number() over (partition by SKU order by UpdateDate desc) rowid 
from Productos) t 
where rowid = 1 
0

試試這個,

SELECT p.StoreId, p.SKU, p.Barcode, p.UpdateDate FROM AProductos p 
JOIN( SELECT StoreId, SKU, MAX(UpdateDate) as MaxTime 
FROM AProductos 
GROUP BY StoreId, SKU 
) r ON p.StoreId = r.StoreId 
AND p.SKU  = r.SKU 
AND p.UpdateDate = r.MaxTime; 
0

那麼,是不是答案明擺着的嗎? SKU只是關鍵的一部分,所以不要使用SKU而不使用其他部分StoreID

SELECT p.StoreId, p.SKU, p.Barcode, p.Fec_Movto 
FROM Productos p 
JOIN 
(
    SELECT StoreId, SKU, MAX(Fec_Movto) as MaxTime 
    FROM Productos 
    GROUP BY StoreId, SKU 
) r ON p.StoreId = r.StoreId 
    AND p.SKU  = r.SKU 
    AND p.Fec_Movto = r.MaxTime; 

另一種方法是排名的行,所以你不必訪問兩次表:

SELECT StoreId, SKU, Barcode, Fec_Movto 
FROM 
(
    SELECT 
    SKU, 
    Fec_Movto, 
    ROW_NUMBER() OVER (PARTITION BY StoreId, SKU ORDER BY Fec_Movto DESC) AS rn 
    FROM Productos 
) ranked 
WHERE rn = 1; 
0

您可以使用OUTER APPLY:

SELECT distinct main.StoreId, main.SKU, b.Barcode, b.UpdateDate 
FROM Productos as main 
Outer Apply (Select Top 1 
        SKU, BarCode, UpdateDate 
      from Productos as sub 
      where main.SKU = sub.SKU 
      Order by sub.UpdateDate desc 
      ) b