简体   繁体   中英

ordering within select - case statement

Is there a way to ordering within a select case statement by a single column only? lets say order in ascending by city only.

SELECT 
StudentLocation = 
CASE
  WHEN @IsRegistered IS NOT NULL AND @IsInClass IS NOT NULL THEN s.InClassLocation
  WHEN @IsRegistered IS NOT NULL AND @IsInClass IS NULL THEN s.OnlineLocation 
  ELSE s.City + ', ' + s.State
END

You left out of your question the table and from/where clause, but assuming s is an alias to the table you're querying, you can use order the same way you always do it:

SELECT 
StudentLocation = 
CASE
  WHEN @IsRegistered IS NOT NULL AND @IsInClass IS NOT NULL THEN s.InClassLocation
  WHEN @IsRegistered IS NOT NULL AND @IsInClass IS NULL THEN s.OnlineLocation 
  ELSE s.City + ', ' + s.State
END
FROM someTable as s
ORDER BY s.City ASC;

Corrected City

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM