Friday, February 22, 2008

How to group some results at the top...

Note: I know the spacing on this post is kinda crazy. Don't have time to fight with blogger's editor right now, so just deal, okay?

Let's say you want to get a list of things back from a query, grouping a particular group of items at the top of your query, and the rest below.

For example, let's say you're getting back a contact list sorted alphabetically by organization, and THEN by contact's last name. Let's say you want all of those that belong to "RandCorp" to show at the top because you're interested in those first. Normally, you could sort by "org" and then by "lastname". Unfortunately, RandCorp comes after AAA Coating in the alpha sort. But what you really want is the randCorp items to be listed first (cause those are the ones you're most interested in, but you also want to see the others).

Here's one way to do it.

SELECT LastName, Org,
CASE WHEN Org = 'RandCorp' THEN 1 ELSE 0 AS keySort

FROM Clients
ORDER BY keySort DESC, Org, LastName

If your data looked like this:


























LastNameOrg
MyersZenith Tech
RadnerAAA Coating
FerrelRandCorp
FarleyZenith Tech
MurphyAAA Coating


This query would return:


























LastNameOrg
FerrelRandCorp
MurphyAAA Coating
RadnerAAA Coating
FarleyZenith Tech
MyersZenith Tech

0 Comments:

Post a Comment

<< Home