2016-11-10 8 views
0

私の質問はこの質問の逆です。TSQL - 最後に特定の値を持つ行を返す方法

TSQL - Is it possible to define the sort order?

は、私はいつも最後にする必要があり、列の値が、2つの特定のレコードに基づいて昇順にソートSQL Serverデータベースから一部のレコードを返すようにしたいです。 (変更する必要がある)

元のSQLは、以下である:

select code_id as CategoryID, code_desc as CategoryDescription 
from codes 
where code_id > '000001' and code_id < '000100' 
order by CategoryDescription 

結果は

  • 000003 ***最初のレコード
  • 000002 ***別のレコードとして返されます
  • 000004アップル
  • 000016書籍
  • 本の000014ケーブル

私は以下の結果(最後のasteriksとの最初の2)欲しい:

  • 000004アップル
  • 000016ブックス
  • 000014ケーブルまず
  • 000003 ***をレコード
  • 000002 ***別のレコード

私は以下のUNION文を試しましたが、結果セットは自動的に昇順にソートされ、その2行はデフォルトで最初に入っています。 code_idのDESCによって

select code_id as CategoryID, code_desc as CategoryDescription 
from codes 
where code_id > '000003' and code_id < '000100' 
--order by categoryDescription 

UNION 

select code_id as CategoryID, code_desc as CategoryDescription 
from codes 
where code_id > '000001' and code_id < '000004' 
+1

は、いくつかのサンプルデータを表示してください、そして順で最初の出力 – TheGameiswar

+0

を期待しますBY、CASE式を使用して2つの特定の値を最後に置きます。列で注文します。 – jarlh

+0

サンプルテーブルとそれから必要な結果を提供することができます。 –

答えて

1

を探していることがあります。

select * from (
    select 'T' as Success, code_id as CategoryID, code_desc as CategoryDescription, 1 as order 
    from codes 
    where code_id > '000003' and code_id < '000100' 

    UNION 

    select 'T' as Success, code_id as CategoryID, code_desc as CategoryDescription, 2 as order 
    from codes 
    where code_id > '000001' and code_id < '000004' 
) x 
order by x.order 
+0

完璧にするために、最後に "、CategoryDe​​scription"を追加する必要があります。 – user1451111

0
select 'T' as Success, code_id as CategoryID, code_desc as CategoryDescription 
from codes 
where (code_id > '000003' and code_id < '000100') or (code_id > '000001' and code_id < '000004') 

ため

あなたのコードが長すぎる、なぜあなたは、このように変更していけませんか?

0

あなたは、あなたがこのような何か行うことができ、その後組合を維持したい場合は、この

select 'T' as Success, code_id as CategoryID, code_desc as CategoryDescription 
from codes 
where (code_id > '000003' and code_id < '000100') OR 
     (code_id > '000001' and code_id < '000004') 
ORDER BY CASE 
      WHEN (code_id > '000003' and code_id < '000100') THEN 1 
      WHEN (code_id > '000001' and code_id < '000004') THEN 2 
     END 
関連する問題