1

I'm trying to get unique product from stock...

stock table:

id - product - quantity
1    2            0
2    3            5
3    2            19
4    4            3
5    2            8

result

id - product - quantity
5    2            8
4    4            3
2    3            5

it's working with

SELECT max(id) as id, 
product
FROM stock 
GROUP by product 
ORDER by id DESC

but I can't get last quantity of product with this query I get:

id - product - quantity
1    2            0
2    3            5
4    4            3

I need latest quantity of the product.

4

3 回答 3

1

您可以将现有查询包装在子查询中并将其连接到表本身,以便您可以获得同一行的其他列。

SELECT  a.*
FROM    stock a
        INNER JOIN
        (
            SELECT  product, MAX(ID) id
            FROM    stock
            GROUP   BY product
        ) b ON  a.product = b.product
                AND a.ID = b.ID
ORDER   BY a.id DESC
于 2013-11-06T15:49:25.560 回答
0

假设您对“最新”的定义是 max(id),我认为最简单的方法是:

SELECT s.id, s.product, s.quantity
FROM stock s
WHERE NOT EXISTS (SELECT 1 FROM stock s2 WHERE s2.product = s.product and s2.id > s.id);

基本上给我股票行,其中没有同一产品的行具有更大的 id。

于 2013-11-06T15:55:19.900 回答
0

您可以使用表与自身的左连接来执行此操作,该表仅过滤没有具有更高 id 和相同产品的行,避免子查询和分组依据,这在大型表上可能非常昂贵:

select p1.id, p1.product, p1.quantity from stock as p1 
left join test as p2 on p1.product = p2.product and p2.id> p1.id
where p2.id is null
order by p1.id desc;
于 2013-11-06T16:07:26.847 回答