2012-07-10 22 views
10

Di seguito è riportato il mio tavoloSQL query di selezione gruppo

Table1

+--------+----------+---------+ 
| amount | make  | product | 
+--------+----------+---------+ 
| 100 | Nokia | Mobiles | 
| 300 | Samesung | Mobiles | 
| 700 | Micromax | Mobiles | 
| 1000 | Karbonn | Mobiles | 
| 500 | Lava  | Mobiles | 
| 100 | Floyer | Gift | 
| 500 | Arichies | Gift | 
| 300 | Feeling | Gift | 
+--------+----------+---------+ 

Ora voglio visualizzare i due più alta quantità per ogni prodotto ...

Quindi voglio costruire query di singola SQL che mi dà il risultato sotto forma seguente ..

+--------+----------+---------+ 
| amount | make  | product | 
+--------+----------+---------+ 
| 1000 | Karbonn | Mobiles | 
| 700 | Micromax | Mobiles | 
| 500 | Arichies | Gift | 
| 300 | Feeling | Gift | 
+--------+----------+---------+ 

gentilmente mi aiuti a costruire tali interrogazione ..

risposta

10

È possibile utilizzare questa soluzione per recuperare il "gruppo-saggio massimo" in base alla amount:

SELECT a.* 
FROM Table1 a 
INNER JOIN Table1 b ON a.product = b.product AND a.amount <= b.amount 
GROUP BY a.amount, a.product 
HAVING COUNT(*) <= 2 

Basta cambiare il 2 al tuttavia molte delle migliori righe che si desidera recuperare per Prodotto.

Se si desidera recuperare le due righe più basse per prodotto, è sufficiente modificare l'indicazione <= nello INNER JOIN in un >=.

Si può giocherellare con questa soluzione qui: SQL-Fiddle Demo

0
select top 2 amount, make, product from table1 
where product='Mobiles' 
order by amount desc 
union 
select top 2 amount, make, product from table1 
where product='Gift' 
order by amount desc 
+0

la risposta non è generale. Cosa succede se hai 100 prodotti? –

0

Si può fare in due modi: 1) Aggiungere colonna indice di riga che rifletterà l'ordine e quindi selezionare tutte le righe con Riga < = 2

SELECT amount, make,product 
FROM 
(SELECT ROW_NUMBER() OVER (PARTITION BY [product] ORDER BY [amount] DESC) AS [RowID],* 
FROM [dbo].[Table1]) RESULT 
WHERE RowID <= 2 

2) Si può anche partecipare al tavolo a se stesso

SELECT a1.* FROM Table1 AS a1 
    LEFT JOIN Table1 AS a2 
    ON a1.product = a2.product AND a1.amount<= a2.amount 
GROUP BY a1.product 
HAVING COUNT(*) <= 2; 
+0

mysql non ha funzioni analitiche. –

1
SELECT a.* 
FROM Table1 a 
INNER JOIN Table1 b ON a.product = b.product AND a.amount <= b.amount 
GROUP BY a.amount, a.product 
HAVING COUNT(*) <= 2 
ORDER BY a.amount desc 

Si prega di fare riferimento a http://sqlfiddle.com/#!2/9ba82/1