Domanda

Supponiamo, ho un tavolo denominato articoli:

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   
.

Qui voglio selezionare il mittente_id, merci_id in ordine decrescente del prezzo da elementi tabella tale che nessuna riga appare più di una volta che contiene lo stesso valore Sender_ID (qui mider_id 2).Ho usato la seguente query, ma era in vana:

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

Il risultato mostra tutte le cinque tuples (record) con le tuple contenenti Sender_ID 2 tre volte in ordine decrescente del tempo. Ma ciò che voglio è visualizzare solo tre record uno di essi avente Sender_ID di 2 con solo il prezzo più alto di 5000. Cosa dovrei fare? La mia uscita prevista è:

sender_id goods_id
   2         c1
   3         b2
   4         d1
.

È stato utile?

Soluzione

Si prega di provare questo

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
.

Altri suggerimenti

Ottieni il prezzo più alto di ciascun gruppo, potresti fare come sotto:

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
.

Prova questo:

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
.

o

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;
.

Puoi usare come questo.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top