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|
--------------------------------
以某种方式我的表看起来,现在我的问题是如何选择每个类别的一个产品,这是该类别中的最新产品,这可能在一个查询中?
我尝试了很多东西,但它太冗长了...请帮助
答案 0 :(得分:1)
也许这样的事情(如果你想要按照最高日期):
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
答案 1 :(得分:0)
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返回额外的空列。
答案 2 :(得分:0)
在Sql server中,您可以使用:
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