2012-03-09 4 views
9

Sto cercando qualcosa di simile questo in SQL Server:PostgreSQL equivalente per TOP n WITH TIES: LIMIT "with tie"?

SELECT TOP n WITH TIES FROM tablename 

so su LIMIT in PostgreSQL, ma fa l'equivalente della esistere sopra? Sono solo curioso perché salverà ogni volta una query in più per me.

Se ho un tavolo Numbers con attributo nums: {10, 9, 8, 8, 2}. Voglio fare qualcosa di simile:

SELECT nums FROM Numbers ORDER BY nums DESC LIMIT *with ties* 3 

Dovrebbe restituire {10, 9, 8, 8} perché prende i primi 3 più il più 8 in quanto si lega l'altra.

risposta

8

Non esiste la clausola WITH TIES in PostgreSQL come in SQL Server.
In PostgreSQL vorrei sostituire questo per TOP n WITH TIES .. ORDER BY <something>:

WITH cte AS (
    SELECT *, rank() OVER (ORDER BY <something>) AS rnk 
    FROM tbl 
    ) 
SELECT * 
FROM cte 
WHERE rnk <= n; 

Per essere chiari, rank() è giusto, dense_rank() sarebbe sbagliato (tornare troppe righe).
Considerate questa citazione dalla documentazione SQL Server (dal link qui sopra):

Ad esempio, se l'espressione è impostato a 5 ma 2 ulteriori righe corrispondenti valori dell'ordine da colonne nella riga 5, la set di risultati conterrà 7 righe .

Il lavoro di WITH TIES è includere tutti i peer dell'ultima fila in alto n come definito dalla clausola ORDER BY. rank() fornisce lo stesso identico risultato.

Per essere sicuri, ho provato con SQL server, ecco uno live demo.
E qui è più conveniente SQLfiddle.

+1

Perchè questo complicato? La funzione rank() farà esattamente ciò che è richiesto? –

+0

@a_horse_with_no_name: hai assolutamente ragione (come ero io all'inizio). Le mie seconde considerazioni non sono state accettate. –

+0

@Erwin: che bello (http://data.stackexchange.com/stackoverflow/query/63525/top-n-with-ties), non sapevo che StackOverflow ha un modulo integrato per eseguire query :-) Anche se l'output di 10,10,9 per 10,9,8,8,2,10 non è corretto se è necessario ottenere i primi 3 (10,9,8) ed elencare tutti quei 10,9,8; che dovrebbe essere: 10,10,9,8,8. 'WITH TIES' potrebbe non essere corretto per alcuni casi problematici: http://stackoverflow.com/questions/2611822/distinct-with-count-and-sql-server-2005/2612456#2612456 –

2

Prova questo:

uscita: 10, 9, 8, 8

with numbers (nums) as (
  values (10), (9), (8), (8), (2) 
)  
SELECT nums FROM Numbers  
WHERE nums in (SELECT DISTINCT nums FROM Numbers ORDER BY nums DESC LIMIT 3) 
ORDER BY nums DESC 

uscita: 10,10,9,8,8

with numbers (nums) as (
    values (10), (9), (8), (8), (2), (10) 
) 
SELECT nums FROM Numbers 
WHERE nums in (SELECT DISTINCT nums FROM Numbers ORDER BY nums DESC LIMIT 3) 
ORDER BY nums DESC