Question

Suppose,I have a table named items:

sender_id receiver_id goods_id price
  2            1          a1   1000
  3            1          b2   2000
  2            1          c1   5000
  4            1          d1   700
  2            1          b1   500   

Here I want to select the sender_id,goods_id in descending order of price from the items table such that no row appears more than once which contains the same sender_id value (here sender_id 2). I used the following query,but was in vain:

select distinct sender_id,goods_id from items where receiver_id=1 order by price desc

The result shows all the five tuples(records) with the tuples containing sender_id 2 thrice in descending order of time.But what I want is to display only three records one of them having sender_id of 2 with only the highest price of 5000. What should I do? My expected output is:

sender_id goods_id
   2         c1
   3         b2
   4         d1
Was it helpful?

Solution

please try this

select sender_id,goods_id from items t1
where not exists (select 1 from items t2
                  where t2.sender_id = t1.sender_id
                    and t2.receiver_id = t1.receiver_id
                    and t2.price > t1.price)
 and receiver_id = 1
order by price desc

OTHER TIPS

Get the highest price of each group, you could do like below:

SELECT T1.*
FROM (
    SELECT
     MAX(price) AS max_price,
     sender_id
    FROM items
    GROUP BY sender_id
) AS T2
INNER JOIN items T1 ON T1.sender_id = T2.sender_id AND T1.price = T2.max_price
WHERE T1.receiver_id=1 
ORDER BY T1.price

Try this:

SELECT i.sender_id, i.goods_id 
FROM items i 
INNER JOIN (SELECT i.sender_id, MAX(i.price) AS maxPrice
            FROM items i WHERE i.receiver_id=1 
            GROUP BY i.sender_id
           ) AS A ON i.sender_id = A.sender_id AND i.price = A.maxPrice
WHERE i.receiver_id=1

OR

SELECT i.sender_id, i.goods_id 
FROM (SELECT i.sender_id, i.goods_id 
      FROM (SELECT i.sender_id, i.goods_id 
            FROM items i WHERE i.receiver_id=1 
            ORDER BY i.sender_id, i.price DESC
           ) AS i 
      GROUP BY i.sender_id
     ) AS i
select distinct (sender_id,goods_id) from items where receiver_id=1 order by price desc;

you can use like this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top