我想从产品表中获取具有最大产品ID的所有记录。产品表中的记录按类别存储,如下所示
Product id Category id Product name Product image
1 1 product 1 path
2 1 Product 2 path
1 2 Product 1 path
2 2 Product 2 path
3 2 Product 3 path
1 3 Product 1 path
我有类似下面的分类表
类别ID类别名称 1类别1 2类别2 3类别3
所以我需要编写一个返回每个类别中最大产品记录的查询(本例中为1,2,3),所以我们得到的结果如
# Product id Category id Product name Product image
1. 2 1 product 2 path
2. 3 2 product 2 path
3. 1 3 product 1 path
注意: - 产品ID是主键,并根据其类别生成 category id是产品表中的外键。 我在我的C#应用程序中使用此查询/数据库。我正在使用 MS-Access。
答案 0 :(得分:0)
好的,这会有所帮助:
"SELECT * From Product WHERE Categoryid=(SELECT Max(Count(*)) from product group by Categoryid)"
答案 1 :(得分:0)
这应该有帮助
SQL Server -
select p.* from
(
select max(productid) productid,categoryid from products group by categoryid
) a join products p on p.productid = a.productid
and p.categoryid = a.categoryid
访问 -
select [p].* from
(
select max(productid) as pid,categoryid from products group by categoryid
) as [a] inner join [products] as [p] on [p].[productid] = [a].pid
and [p].categoryid = [a].categoryid