如何从以下查询中获得每种产品的前1名记录?
SELECT DISTINCT o.product, o.orderID, od.qty, od.amount FROM
orders o, orderdetails od WHERE o.orderID=od.orderID
Product OrderID Qty Amount
Pen 11222 10 100.00
Pen 11223 5 50.00
Pen 11224 1 10.00
Book 22222 1 12.00
Book 2223 5 10.00
Scale 1111 2 9.00
Scale 2222 1 2.00
答案 0 :(得分:1)
SELECT
o.Product, MAX(od.QTy)
FROM
orders o
INNER JOIN orderdetails od ON o.orderID=od.orderID
GROUP BY o.Product
或
SELECT
o.Product, MAX(od.Amount)
FROM
orders o
INNER JOIN orderdetails od ON o.orderID=od.orderID
GROUP BY o.Product
取决于您认为的“顶级”产品。
答案 1 :(得分:0)
顶部基于什么?大多数?如果有的话试试这个
Select * From Orders O
Where OrderId =
(Select Max(orderId) From Orders
Where product = P.product
And Qty = (Select Max(Qty)
From orders
Where Product = O.Product))
否则,如果Top表示其他内容更改了最后三行,则找到满足“Top”定义的记录的Orderid
答案 2 :(得分:0)
试一试......
Select o.product, o.orderID, od.qty, od.amount
from orders o, orderdetails od
where o.orderID = od.orderID
and o.orderID in (Select Min(o.orderId)
From orders o
Group By o.product)