具有复合主键的表中具有MAX(DATE)的GROUP BY

时间:2016-09-21 22:08:51

标签: sql sql-server greatest-n-per-group

我正在尝试列出表中每个SKU的BarCode,但BarCode在某些情况下是不同的,所以我想从一个sku中获取一个条形码,返回的条形码应该是最近更新的条形码。

示例:

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

但问题在于主键是复合主键,因此根本不起作用。

4 个答案:

答案 0 :(得分: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

答案 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;

答案 2 :(得分: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;

答案 3 :(得分: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