首页 > 解决方案 > 在 case when 语句中按列号排序表

问题描述

是否可以在语句的情况下使用列号订购表格?这是代码

;WITH
    Table1 AS (....),
    Table2 AS (....)

INSERT INTO #temp
SELECT TOP 50 
    one.id,
    one.sales,
    two.count,
    one.sales * two.count as 'Volume %'        
FROM Table1 one,
INNER JOIN Table2 two on one.id = two.id
ORDER BY 
    CASE  @order
        WHEN 1 THEN 
            7             ---Column number here since [Volume %] giving me an error
        WHEN 2 THEN
            10            ---Column number
        END
    DESC

标签: sqlsql-servertsql

解决方案


我做了一些测试并了解到,虽然直接的 ORDER BY 可以引用列别名(即使是那些带有空格字符的),但 ORDER BY 中的 CASE 表达式不能。我从来没有在任何地方看到过这个记录,但我自己测试过。

您的别名中是否有特殊字符并不重要。如果你只做了:

one.sales * two.count as Volume   

您仍然会收到以下错误:

  ORDER BY CASE @order
   WHEN 1 THEN Volume

而且我怀疑这与您不能使用列号的原因相同。

作为解决此问题的可靠方法,我的建议是:

  ORDER BY CASE @order
   WHEN 1 THEN  one.sales * two.count

推荐阅读