选择在多列上过滤的最新行

时间:2019-03-18 22:04:34

标签: sql sql-server linq ef-core-2.2

我有一个sql表

+------+-----------+-----------+--------+--------------+
| rowID| location | fk_Item_ID |Balance |Inventory_Date|
+------+-----------+-----------+--------+--------------+
| 1    | 1         | p1        |500     |2019-01-10    |
| 2    | 1         | p2        |450     |2019-01-05    | 
| 3    | 2         | p2        |500     |2019-01-10    |
| 4    | 1         | p1        |300     |2019-01-15    |
| 5    | 1         | p1        |350     |2019-01-16    |
+------+-----------+-----------+--------+--------------+

我试图编写一条SQL语句,最好是LINQ,以便按日期获取最新行,然后获取每个位置每个部分的最大行数

SELECT * FROM Inventory_Log AS l1
WHERE 
    rowID IN (
        SELECT MAX(rowID) FROM Inventory_Log 
        WHERE 
            fk_Item_ID = l1.fk_Item_ID 
            AND Inventory_Date = (
                SELECT MAX(Inventory_Date) 
                FROM Inventory_Log 
                WHERE fk_Item_ID = l1.fk_Item_ID
            )
    )
ORDER by l1.fk_Item_ID

预期结果:

+------+-----------+-----------+--------+--------------+
| rowID| location | fk_Item_ID |Balance |Inventory_Date|
+------+-----------+-----------+--------+--------------+
| 2    | 1         | p2        |450     |2019-01-05    | 
| 3    | 2         | p2        |500     |2019-01-10    |
| 5    | 1         | p1        |350     |2019-01-16    |
+------+-----------+-----------+--------+--------------+

我不确定如何在同一部分中包含多个位置 它将放入以下课程

public class _ItemLocations
{
   public string Item_ID { get; set; }
   public string Location { get; set; }
   public decimal Qty { get; set; }
}

我还没有在LINQ中尝试过,因为我正在sql中购物

1 个答案:

答案 0 :(得分:1)

在SQL Server中,使用ROW_NUMBER()

SELECT * FROM (
    SELECT 
        i.*, 
        ROW_NUMBER() OVER(PARTITION BY location, fk_Item_ID ORDER BY Inventory_Date DESC, rowID DESC) rn
    FROM Inventory_Log i
) x WHERE rn = 1

注意:我不清楚您希望对rowID进行哪种排序,因为您说过要对记录按Inventory_Date进行排序:我将其用作第二种排序标准(因此,它将如有需要,请打破Inventory_Date上的领结)。

Demo on DB Fiddle

rowID | location | fk_Item_ID | Balance | Inventory_Date      | rn
----: | -------: | :--------- | ------: | :------------------ | :-
    2 |        1 | p2         |     450 | 05/01/2019 00:00:00 | 1 
    3 |        2 | p2         |     500 | 10/01/2019 00:00:00 | 1 
    5 |        1 | p1         |     350 | 16/01/2019 00:00:00 | 1