在select - case语句中排序

时间:2017-06-27 17:36:31

标签: sql sql-server

有没有办法只在一个列的select case语句中进行排序?让我们说按城市递增的顺序。

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

1 个答案:

答案 0 :(得分:0)

您从表格和/ where子句中删除了您的问题,但假设s是您要查询的表的别名,您可以按照与以往相同的方式使用订单:

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;

更正了城市