[英]SQL Query select last entry for each product and the one previous the last
Good Afternoon, 下午好,
I'm trying to build a simple inventory system and i wish i could have a query able to select the last entry for each product (component ; ref) and also the one just before the last one for each product (to compare). 我正在尝试构建一个简单的库存系统,希望我可以有一个查询,该查询能够选择每种产品(组件;参考)的最后一个条目,也可以选择每种产品的最后一个条目的前一个条目(进行比较)。
This is what i have so far : 这是我到目前为止所拥有的:
My query so far is : 到目前为止,我的查询是:
SELECT u1.*
FROM $usertable u1
JOIN (
SELECT component, ref, MAX(date) date
FROM $usertable
GROUP BY component, ref
) u2
USING(component, ref, date) ORDER BY component ASC, ref ASC
Can you please help me to figure out the solution ? 您能帮我找出解决方案吗?
You can do so by using a subquery in where clause 您可以通过在where子句中使用子查询来实现
SELECT u1.*
FROM $usertable u1
WHERE (
SELECT COUNT(*)
FROM $usertable u2
WHERE u2.component= u1.component
AND u2.ref= u1.ref
AND u2.date>= u1.date
) <= 2
ORDER BY component ASC, ref ASC
It should work. 它应该工作。 http://www.sqlfiddle.com/#!2/288980/1 http://www.sqlfiddle.com/#!2/288980/1
You could try specifying the Join
condition. 您可以尝试指定Join
条件。
SELECT u1.*
FROM $usertable u1
JOIN (
SELECT component, ref, MAX(date) date
FROM $usertable
GROUP BY component, ref
) u2
on u2.component = u1.component
and u2.ref = u1.ref
and u2.date = u1.date
ORDER BY component ASC, ref ASC
http://www.sqlfiddle.com/#!2/288980/1 http://www.sqlfiddle.com/#!2/288980/1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.