-1

エイリアスに基づいてセレクションを注文しようとしていますが、方法がわかりません。次に例を示します。

select distinct top 100 id, 
                    col1, 
                    col2, 
                    CASE WHEN @orderFormat = 'this' then col1
                         WHEN @orderFormat = 'that' then col2
                    END as orderby
from table
where col1 = like '%'
order by Len(orderby) asc, orderby asc

エイリアス「orderby」を引数として渡すと、無効な列として報告されます。

私の目標は、可変列を英数字順に並べられるようにすることです。'order by Len(orderby) asc、orderby asc は機能しますが、エイリアスでは機能しないことを知っています。

誰かがこれを回避する良い方法を知っていますか、それとも私が何か間違ったことをしているのですか?

ありがとう!

編集:

私はこれに選択機能を取り除くことができました:

select top 200 Clip_Name as orderby
               from Clips
order by       Len(orderby) asc, orderby asc

Clip_Name は として宣言されcolumn Clip_Name(nvarchar, not null)ます。Microsoft SQL Server 2008 R2 Edition のエラーは ですMsg 207, Level 16, State 1, Line 1 Invalid column name 'orderby'

ただし、これは機能します (エイリアスなし):

select top 200 Clip_Name 
               from Clips 
order by len(FLE_ID) desc, FLE_ID desc
4

2 に答える 2

5

を使用している場合は、実際にリストDISTINCTにある式でのみ並べ替えることができます。SELECTそこにない列、エイリアス、または式を参照することはできません。考えられる回避策の 1 つを次に示しますが、実際には単純に を削除する方がよいDISTINCT場合があります (同じ行が 2 つある場合idは、スキーマまたは少なくともその列の名前に重大な問題があります)。

select distinct top 100 id, 
                    col1, 
                    col2, 
                    CASE WHEN @orderFormat = 'this' then col1
                         WHEN @orderFormat = 'that' then col2
                    END as orderby,
    len(CASE WHEN @orderFormat = 'this' then col1
             WHEN @orderFormat = 'that' then col2
        END) AS ignore_this_column
from table
where col1 like '%'
order by ignore_this_column, orderby;

式を繰り返す必要がないように、はるかに単純に表現されています (また、不要な なしでDISTINCT):

;WITH x AS 
(
  SELECT id, col1, col2, 
    orderby = CASE @orderFormat
      WHEN 'this' THEN col1
      WHEN 'that' THEN col2
    END
  FROM dbo.table
  WHERE col1 LIKE '%' -- necessary?
)
SELECT id, col1, col2
  FROM x
  ORDER BY LEN(orderby), orderby;
于 2013-03-11T16:10:28.913 に答える
1

あなたが最初のクエリであり、DISTINCT を削除する必要があるという議論に基づいて、これは機能します:

select top 100 id, 
        col1, 
        col2, 
        CASE WHEN @orderFormat = 'this' then col1
             WHEN @orderFormat = 'that' then col2
        END as orderby
from t
order by Len(CASE WHEN @orderFormat = 'this' then col1
                  WHEN @orderFormat = 'that' then col2
             END) asc, orderby asc
于 2013-03-12T16:21:03.670 に答える