ORDER BY子句中的MSSql列别名

时间:2018-12-07 09:13:37

标签: sql-server

我有一个复杂的查询,例如:

SELECT O.OrderNo, 
**COMPLEX SELECT** as Total
FROM Order O

ORDER BY 
CASE WHEN @SortOrder = 'Ascending' THEN 1
      ELSE
           CASE 
                WHEN @SortBy = 'Total' THEN Total
           END
      END ASC,
      CASE WHEN @SortOrder = 'Descending' THEN 1
      ELSE
           CASE 
                WHEN @SortBy = 'Total' THEN Total
           END
      END DESC

但是我得到“无效的列名总计”。 我正在使用Sql Server 2016。

为什么我不能按别名订购?我不想使用索引。

2 个答案:

答案 0 :(得分:1)

您可以使用子查询或cte

select  * from (select *,'' total from orders)A
ORDER BY 
CASE WHEN @SortOrder = 'Ascending' THEN 1
      ELSE
           CASE 
                WHEN @SortBy = 'Total' THEN Total
           END
      END ASC,
      CASE WHEN @SortOrder = 'Descending' THEN 1
      ELSE
           CASE 
                WHEN @SortBy = 'Total' THEN Total
           END
      END DESC

答案 1 :(得分:1)

您可以尝试使用CTE:

AWSTemplateFormatVersion : '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  POCLambdaExecutionRole:
  Type: 'AWS::IAM::Role'
  SAMLocal:
    Type: AWS::Serverless::Function
    Properties:
      Handler: SAMLocal.lambda_handler
      Runtime: python2.7
    TracingConfig:
      Mode: Active
      Environment:
        Variables:
          dev_table: "MessageQueue"
      Events:
        SAMLocal:
          Type: Api
          Properties:
            Path: /
            Method: GET
  SAMLocal1:
    Type: AWS::Serverless::Function
    Properties:
      Handler: SAMLocal.lambda_handler
      Runtime: python2.7