次の表があります:
key | date | flag
--------------------------
1 now() true
2 now() - 1 hour true
3 now() + 1 hour true
4 now() false
5 now() - 1 hour false
6 now() + 1 hour false
次のような並べ替えをしたいです:
- まず、 を含むすべての行
flag = false
。これらの行は で並べ替える必要がありますdate asc
。 - 次に、他のすべての行 (
flag = true
) です。ただし、これらの行は で並べ替える必要がありますdate desc
。
次のクエリは正しいですか?
(
select *
from test
where flag = false
order by date asc
)
union all
(
select *
from test
where flag = true
order by date desc
)
これを行うより良い方法はありますか?union all
行をソートしたままにして、2 つの内部クエリの出力を連結するだけでしょうか?
order by
条件に基づいて内の列を繰り返す方法がわかりません。
アップデート
Fiddle はここにあります:http://rextester.com/FFOSS79584
ベストアンサー1
CASE
条件付き順序は、次のように を使用して実行できます。
select *
from test
order by
flag
, case when flag then date end desc
, case when not flag then date end asc