TOP WITH TIES in Vertica?

Moderator: NorbertKrupa

Post Reply
debfawn
Beginner
Beginner
Posts: 47
Joined: Tue Jan 29, 2013 2:30 pm

TOP WITH TIES in Vertica?

Post by debfawn » Thu Mar 26, 2015 2:15 pm

SQL Server has a TOP n WITH TIES command that will return the greatest n values and includes ties (those that are equal).

In Vertica we have the LIMIT command and I can get the TOP 3 values using a LIMIT 3 in combination with ordering the data descending...

Code: Select all

dbadmin=> select * from top;
 numbers
---------
       5
       5
       1
       2
       3
       4
(6 rows)

dbadmin=> select * from top order by numbers desc limit 3;
 numbers
---------
       5
       5
       4
(3 rows)
But want I want is 5, 5, 4 and 3. Using the WITH TIES option in SQL Server can get me this.

How can I do this in Vertica?

User avatar
JimKnicely
Site Admin
Site Admin
Posts: 1825
Joined: Sat Jan 21, 2012 4:58 am
Contact:

Re: TOP WITH TIES in Vertica?

Post by JimKnicely » Thu Mar 26, 2015 8:07 pm

Here is one way:

Code: Select all

dbadmin=> SELECT numbers FROM top WHERE numbers IN (SELECT DISTINCT numbers FROM top ORDER BY numbers DESC LIMIT 3) ORDER BY numbers DESC;
 numbers
---------
       5
       5
       4
       3
(4 rows)
But I wouldn't expect great performance out of that query on a large data set :D
Jim Knicely

Image

Note: I work for Vertica. My views, opinions, and thoughts expressed here do not represent those of my employer.

scutter
Master
Master
Posts: 302
Joined: Tue Aug 07, 2012 2:15 am

Re: TOP WITH TIES in Vertica?

Post by scutter » Thu Mar 26, 2015 9:27 pm

Use the DENSE_RANK() analystic function?

select numbers from (
select numbers, dense_rank() over (order by numbers desc) as rk from top
) q
where rk <= 3
order by rk;

5
5
4
3
Sharon Cutter
Vertica Consultant, Zazz Technologies LLC

User avatar
JimKnicely
Site Admin
Site Admin
Posts: 1825
Joined: Sat Jan 21, 2012 4:58 am
Contact:

Re: TOP WITH TIES in Vertica?

Post by JimKnicely » Fri Mar 27, 2015 12:14 pm

Nice scutter! A much better solution!
Jim Knicely

Image

Note: I work for Vertica. My views, opinions, and thoughts expressed here do not represent those of my employer.

debfawn
Beginner
Beginner
Posts: 47
Joined: Tue Jan 29, 2013 2:30 pm

Re: TOP WITH TIES in Vertica?

Post by debfawn » Sat Mar 28, 2015 11:10 am

Awesome as usual! Thanks!!!

Post Reply

Return to “Vertica SQL”