Voglio trovare il 2 °, il 3 ° valore massimo di una colonna
È possibile ordinare la colonna in formato decrescente e quindi ottenere il valore dall'ennesima riga.
MODIFICARE::
Aggiornato come da richiesta di commento.WARNINGcompletamente non testato!
SELECT DOB FROM (SELECT DOB FROM USERS ORDER BY DOB DESC) WHERE ROWID = 6
Qualcosa di simile a quanto sopra dovrebbe funzionare per Oracle ... potresti dover ottenere subito la sintassi!
Si consideri la seguente tabella Employee con una singola colonna per lo stipendio.
.__ + ------ + . | Sal | + ------ + | 3500 | | 2500 | | 2500 | | 5500 | | 7500 | + ------ +
La seguente query restituirà l'elemento Nth Maximum.
select SAL from EMPLOYEE E1 where
(N - 1) = (select count(distinct(SAL))
from EMPLOYEE E2
where E2.SAL > E1.SAL )
Per es. quando è richiesto il secondo valore massimo,
select SAL from EMPLOYEE E1 where
(2 - 1) = (select count(distinct(SAL))
from EMPLOYEE E2
where E2.SAL > E1.SAL )
.__ + ------ + . | Sal | + ------ + | 5500 | + ------ +
Non hai specificato quale database, su MySQL puoi fare
SELECT column FROM table ORDER BY column DESC LIMIT 7,10;
Salteresti il primo 7, e poi otterrai i dieci più alti.
Anche in questo caso potrebbe essere necessario correggere il database, ma se si desidera il 2 ° valore superiore in un set di dati che potenzialmente ha il valore duplicato, è consigliabile eseguire anche un gruppo:
SELECT column
FROM table
WHERE column IS NOT NULL
GROUP BY column
ORDER BY column DESC
LIMIT 5 OFFSET 2;
Salteresti i primi due, e poi ti darò i successivi cinque più alti.
Pure SQL (nota: consiglierei l'uso di funzionalità SQL specifiche per il tuo DBMS poiché probabilmente sarà più efficiente). Questo ti darà il n + 1 ° valore più grande (per diventare più piccolo, capovolgi il <). Se hai duplicati, fallo COUNT (DISTINCT VALUE) ..
select id from table order by id desc limit 4 ;
+------+
| id |
+------+
| 2211 |
| 2210 |
| 2209 |
| 2208 |
+------+
SELECT yourvalue
FROM yourtable t1
WHERE EXISTS( SELECT COUNT(*)
FROM yourtable t2
WHERE t1.id <> t2.id
AND t1.yourvalue < t2.yourvalue
HAVING COUNT(*) = 3 )
+------+
| id |
+------+
| 2208 |
+------+
(Nome tabella = Studente, Nome colonna = segno)
select * from(select row_number() over (order by mark desc) as t,mark from student group by mark) as td where t=4
È possibile trovare l'ennesimo valore maggiore della colonna utilizzando la seguente query:
SELECT * FROM TableName a WHERE
n = (SELECT count(DISTINCT(b.ColumnName))
FROM TableName b WHERE a.ColumnName <=b.ColumnName);
Select max(sal)
from table t1
where N (select max(sal)
from table t2
where t2.sal > t1.sal)
Per trovare il nth max sal.
select column_name from table_name
order by column_name desc limit n-1,1;
dove n = 1, 2, 3, .... nth valore massimo.
Ecco un metodo per Oracle. Questo esempio ottiene il 9 ° valore più alto. Basta sostituire il 9 con una variabile bind contenente la posizione che stai cercando.
select created from (
select created from (
select created from user_objects
order by created desc
)
where rownum <= 9
order by created asc
)
where rownum = 1
Se si desidera l'ennesimo valore univoco, si aggiungerà DISTINCT al blocco di query più interno.
SELECT * FROM tablename
WHERE columnname<(select max(columnname) from tablename)
order by columnname desc limit 1
MySQL:
select distinct(salary) from employee order by salary desc limit (n-1), 1;
(TableName = Student, ColumnName = Mark):
select *
from student
where mark=(select mark
from(select row_number() over (order by mark desc) as t,
mark
from student group by mark) as td
where t=2)
Penso che la query qui sotto funzionerà perfettamente su Oracle SQL ... l'ho provato io stesso ..
Informazioni relative a questa query: questa query utilizza due tabelle denominate employee
e department
con colonne in impiegato denominate: name
(nome impiegato), dept_id
(comune a dipendente e reparto), salary
E colonne nella tabella di dipartimento: dept_id
(comune anche per la tabella dei dipendenti), dept_name
SELECT
tab.dept_name,MIN(tab.salary) AS Second_Max_Sal FROM (
SELECT e.name, e.salary, d.dept_name, dense_rank() over (partition BY d.dept_name ORDER BY e.salary) AS rank FROM department d JOIN employee e USING (dept_id) ) tab
WHERE
rank BETWEEN 1 AND 2
GROUP BY
tab.dept_name
grazie
Soluzione per trovare il valore Nth massimo di una particolare colonna in SQL Server:
Tavolo dei dipendenti:
Tabella delle vendite:
Dati della tabella dei dipendenti:
==========
Id name
=========
6 ARSHAD M
7 Manu
8 Shaji
Dati della tabella delle vendite:
=================
id emp_id amount
=================
1 6 500
2 7 100
3 8 100
4 6 150
5 7 130
6 7 130
7 7 330
Interrogare per scoprire i dettagli di un dipendente che ha la vendita più alta/Nil più alto venditore
select * from (select E.Id,E.name,SUM(S.amount) AS 'total_amount' from employee E INNER JOIN Sale S on E.Id=S.emp_id group by S.emp_id,E.Id,E.name ) AS T1 WHERE(0)=( select COUNT(DISTINCT(total_amount)) from(select E.Id,E.name,SUM(S.amount) AS 'total_amount' from employee E INNER JOIN Sale S on E.Id=S.emp_id group by S.emp_id,E.Id,E.name )AS T2 WHERE(T1.total_amount<T2.total_amount) );
Nel WHERE (0) sostituisce 0 con n-1
Risultato:
========================
id name total_amount
========================
7 Manu 690
Puoi semplificare in questo modo
SELECT MIN(Sal) FROM TableName
WHERE Sal IN
(SELECT TOP 4 Sal FROM TableName ORDER BY Sal DESC)
Se il Sal contiene valori duplicati, usa questo
SELECT MIN(Sal) FROM TableName
WHERE Sal IN
(SELECT distinct TOP 4 Sal FROM TableName ORDER BY Sal DESC)
il 4 sarà l'ennesimo valore può avere qualsiasi valore più alto come 5 o 6 ecc.
Select min(fee)
from fl_FLFee
where fee in (Select top 4 Fee from fl_FLFee order by 1 desc)
Cambia numero quattro con N.
select sal,ename from emp e where
2=(select count(distinct sal) from emp where e.sal<=emp.sal) or
3=(select count(distinct sal) from emp where e.sal<=emp.sal) or
4=(select count(distinct sal) from emp where e.sal<=emp.sal) order by sal desc;
In PostgreSQL, per trovare l'N-esimo stipendio più alto dalla tabella Employee.
SELECT * FROM Employee WHERE salary in
(SELECT salary FROM Employee ORDER BY salary DESC LIMIT N)
ORDER BY salary ASC LIMIT 1;
query mysql : supponiamo di voler trovare l'ennesima tabella stipendi massima del dipendente
select salary
form employee
order by salary desc
limit n-1,1 ;
Semplice query SQL per ottenere i dettagli del dipendente che ha N ° MAX Salary
nella tabella Employee
.
sql> select * from Employee order by salary desc LIMIT 1 OFFSET <N - 1>;
Considera la struttura della tabella come:
Dipendente ( Id [int chiave primaria auto_increment], Nome [varchar (30)], Salary [int]);
Esempio:
Se hai bisogno del terzo stipendio MAX
nella tabella sopra, la query sarà:
sql> select * from Employee order by salary desc LIMIT 1 OFFSET 2;
Analogamente:
Se hai bisogno dell'8 ° stipendio MAX
nella tabella sopra, la query sarà:
sql> select * from Employee order by salary desc LIMIT 1 OFFSET 7;
NOTA: Quando devi ottenere il valore Nth
MAX
dovresti fornireOFFSET
as (N - 1).
Come questo puoi fare lo stesso tipo di operazione in caso di stipendio in ordine crescente.
In SQL Server, basta fare:
select distinct top n+1 column from table order by column desc
E poi butta via il primo valore, se non ne hai bisogno.
Un altro per Oracle che utilizza le funzioni analitiche:
select distinct col1 --distinct is required to remove matching value of column
from
( select col1, dense_rank() over (order by col1 desc) rnk
from tbl
)
where rnk = :b1
Ho appena tirato fuori questa domanda cercando la risposta da solo, e questo sembra funzionare per SQL Server 2005 (derivato da Soluzione di Blorgbeard ):
SELECT MIN(q.col1) FROM (
SELECT
DISTINCT TOP n col1
FROM myTable
ORDER BY col1 DESC
) q;
In effetti, è un SELECT MIN(q.someCol) FROM someTable q
, con il primo n della tabella richiamato dalla query SELECT DISTINCT...
.
per SQL 2005:
SELECT col1 from
(select col1, dense_rank(col1) over (order by col1 desc) ranking
from t1) subq where ranking between 2 and @n
Risposta: Top second:
select * from (select * from deletetable where rownum <=2 order by rownum desc) where rownum <=1