You are here: Re: sorting twice?! « MsSQL Server « IT news, forums, messages
Re: sorting twice?!

Posted by Erland Sommarskog on 10/02/67 11:51

Tim (Citizen10Bears@gmail.com) writes:
> here's a good one for you...
>
> I want to return the last 20 records I have modified. I have a
> datemodified field - excellent.
> So I run a query to select the top 20 when ordered by datemodified
> desc.
> But now I have these results I want them sorted by companyname.
>
> Is this possible?

Sure. With derived tables (almost) everything is possible:

SELECT ...
FROM (SELECT TOP 20 ...
FROM tbl
ORDER BY datemodified DESC) AS x
ORDER BY companyname

A derived table is a verital temp table within the query so speak, and
is an immensly powerful tool to build complex queries. Important to know
is that the optimizer is very good at recasting computation order to get
better performance. (Although in this particular case it is not likely
to happen because of the TOP operator.)


--
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация