简体   繁体   English

SQL - Select with group by, 从寄存器中获取具有最大值(日期)的数据

[英]SQL - Select with group by, Get data from the register with the max(date)

I have two tables in the database: Product and ProductVersion , each product can have n ProductVersions.我在数据库中有两个表: ProductProductVersion ,每个产品可以有 n 个 ProductVersions。 ProductVersion has this fields ( Id, name, origin, date, provider ) ProductVersion 有这个字段(Id、name、origin、date、provider)

I want a query where I get a product info and in the same register the info of the productversion with the max date, something like this:我想要一个查询,我在其中获取产品信息,并在同一个注册中使用最大日期的 productversion 信息,如下所示:

select
p.ProductId, p.ProductName , max(pv.date), name of  max(pv.date), origin of  max(pv.date)
from Product p Join ProductVersion pv on p.ProductId = pv.ProductId
where userId = 'test_user'
group by p.Id

I want to create a view to call from c#, I am working with linq but the performace for this case is not good, so I am trying with a view with the info I need.我想创建一个从 c# 调用的视图,我正在使用 linq 但这种情况下的性能不好,所以我正在尝试使用我需要的信息的视图。 Something like this I want to achieve with a SQL query.我想用 SQL 查询来实现这样的事情。

var result =
_context.ProductVersion
    .Where(x => x.UserId == userId)
    .GroupBy(x => x.ProductId)
    .Select(group => group.OrderByDescending(x => x.Date).FirstOrDefault())
    .Include(x => x.Product)
    .ToList();

I understand that you want the latest row from ProductVersion for each Product .我了解您需要ProductVersion中每个Product的最新行。 A simple and efficient method in SQL Server is a lateral join: SQL 服务器中一个简单有效的方法是横向连接:

create view myview as
select p.*, pv.name, pv.origin, pv.date, pv.provider
from product p
cross apply (
    select top (1) *
    from productVersion pv
    where p.productId = pv.productId
    order by pv.date desc
)

This should do it.这应该这样做。

DECLARE @userID NVARCHAR(100) = N'test_user'

WITH cte
AS
(
    SELECT
        p.ProductID
        ,p.ProductName
        ,pv.Date as VersionDate
        ,pv.Name as VersionName
        ,pv.Origin as VersionOrigin
        ,ROW_NUMBER() OVER (PARTITION BY p.ProductID ORDER BY pv.Date DESC) as PartitionID
    FROM product p
        inner join ProductVersion  pv on p.ProductId = pv.ProductID
    WHERE userID = @userID
)

SELECT 
    ProductID
    ,ProductName
    ,VersionDate
    ,VersionName
    ,VersionOrigin
FROM cte
WHERE PartitionID = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM