[英]how to select one item of each category from a table where a category is entered multple times
Product table
_________________________________
|id |name |category |date |
---------------------------------
|1 |p1 |1 |13586486|
---------------------------------
|2 |p2 |2 |13586445|
---------------------------------
|3 |p3 |1 |13567456|
---------------------------------
|5 |p5 |3 |13586422|
--------------------------------
|6 |p6 |3 |13586678|
--------------------------------
|7 |p7 |1 |13586495|
--------------------------------
这样我的桌子看起来就好了,现在我的问题是如何选择每个类别的一种产品该类别中哪个是最新的,是否可以在单个查询中完成? 我尝试了很多事情,但时间太长...请帮助
也许是这样的(如果您想在最高日期使用):
SELECT
*
FROM
Product AS t1
JOIN
(
SELECT
MAX(t.date) AS date,
t.category
FROM
Product AS t
GROUP BY
t.category
)
AS maxCat
ON maxCat.date=t1.date
AND maxCat.category=t1.category
如果您想要最高的产品ID,则可以执行以下操作:
SELECT
*
FROM
Product AS t1
JOIN
(
SELECT
MAX(t.id) AS id,
t.category
FROM
Product AS t
GROUP BY
t.category
)
AS maxCat
on maxCat.id=t1.id
select p1.* from Product p1 left join Product p2 on p1.category = p2.category and p1.id < p2.id where p2.id is null
这将根据最新ID为您提供最新记录,因为没有其他字段可以找到添加记录的时间。
编辑已更改的select * from
以select p1.* from
,它不会从表p2中返回多余的空列。
在Sql服务器中,您可以使用以下命令:
with productWithRows as(
select row_number() over (partition by category order by date desc) as rownb,*
from product
) as productWithRows,
select * from productWithRows where rownb=1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.