How to get last two Sales' (by date) Product and Customer details from two separate tables in MySQL?

huangapple go评论107阅读模式
英文:

How to get last two Sales' (by date) Product and Customer details from two separate tables in MySQL?

问题

我有两个表,一个是产品表

另一个是销售表

销售表中有日期,我想获取每个产品的最后两次购买记录,包括(产品名称,产品ID,数量,客户名称,客户ID),并按日期排序,但我不知道如何操作。

我尝试使用union,但无法限制到每个产品的最后两个订单(或已购买的产品)。

英文:

I have two tables 1 is Products Table

How to get last two Sales' (by date) Product and Customer details from two separate tables in MySQL?

Another is the Sales Table

How to get last two Sales' (by date) Product and Customer details from two separate tables in MySQL?

The sales table have dates in them, I want to get the last two purchase of each product with it's (ProductName, ProductID, Qty, CustName, CustID) ordered by date and I don't know how to go about doing that.

I tried using union but I can't limit it to last two orders of each product (or the products that has been purchased).

答案1

得分: 0

典型解决方案是使用 row_number():

select P.ProductId, ProductName, CustId, CustName, Date
from Products P
left join (
  select CustId, CustName, ProductId, Date,
         row_number() over (partition by ProductId 
                            order by Date desc, CustId desc) as rn 
  from Sales) LastSales
  on P.ProductId = LastSales.ProductId and LastSales.rn <= 2

如果有多行在完全相同的时间卖出,上面的查询只返回其中两行。如果您想显示所有行,请使用 rank() 替代 row_number():

rank() over (partition by ProductId order by Date desc)

dbfiddle 演示链接

英文:

Typical solution is row_number():

select P.ProductId, ProductName, CustId, CustName, Date
from Products P
left join (
  select CustId, CustName, ProductId, Date,
         row_number() over (partition by ProductId 
                            order by Date desc, CustId desc) as rn 
  from Sales) LastSales
  on P.ProductId = LastSales.ProductId and LastSales.rn &lt;= 2

In case there are several rows sold exactly at the same time above query returns only two of them. If you want to show all use rank() instead of row_number():

rank() over (partition by ProductId order by Date desc)

dbfiddle demo

huangapple
  • 本文由 发表于 2023年5月10日 13:50:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76215260.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定