2012-07-10 2 views
1

하나의 쿼리에서 몇 가지 조건/우선 순위를 사용하여 정렬 할 때 하나의 테이블이 필요합니다. '사용자'라는 이름의 테이블 예를 들어 sql 쿼리 사용자 지정 순서가 하나의 테이블

는 5 열 함께 제공 :

연령, 성별, 생일 null이 될 수있는 경우
userID 
userName 
age 
gender 
birthday 

, 나는 쿼리가 테이블의 행을 반환 바랍니다 의 우선 순위 :

1. Age, gender and birthday is not null, 
2. Age, gender is not null, 
3. Age is not null, 
4. Then the rest of the rows 

나는 (어쩌면 내가 잘못 쿼리) IF에 의해 UNION, UNION ALL 및 ORDER으로하는 듯했지만 결과를 달성하기 위해 관리 didnt한다.

누군가 나를 도와 줄 수 있기를 바랍니다. 고맙습니다.

+0

당신은 등, MySQL은, 오라클, SQL 서버를 사용하고 있습니까? –

답변

0

이것은에 의해 주문하는 간단한 문제입니다 ia 나중에 (이름이나 뭐든간에).

예를 들어, 각각의 경우에서 내림차순으로 연령을 기준으로 정렬합니다 :

order by (case when age is not null and birthday is not null and gender is not null then 1 
       when age is not null and birthday is not null then 2 
       when age is not null then 3 
       else 4 
      end), 
     age desc 
+0

안녕하세요, "1", "2", "4"는 무엇을 의미합니까? 표시 순서입니까? –

+0

실제로는 1, 2, 3, 4 (세 번째 오타)를 의미합니다. 예, 이것들은 order by에 의해 사용되는 값입니다. 그래서 첫번째 조건이 먼저오고 계속됩니다. –

+0

및 나이별로 내림차순으로 정렬하려면 어떻게합니까? –

3

귀하의 질문은 각 우선 순위 충족해야하는 조건이 명확하지 않지만이의 아이디어를 얻을 것이다 :

select * 
from  mytable 
order by 
     case when age is null and gender is null and birthday is null then 1 
       when age is null and gender is null and birthday is not null then 2 
       when age is null and gender is not null and birthday is not null then 3 
       when age is not null and gender is not null and birthday is not null then 4 
       else 5 
     end 

편집 : 나는 때문에 질문이 잘못 읽을 생각을 당신은 추가 정렬 criter을 추가 할 수 있습니다

order by (case when age is not null and birthday is not null and gender is not null then 1 
       when age is not null and birthday is not null then 2 
       when age is not null then 3 
       else 4 
      end) 

: 형식의 부족과 내가 NOT NULL을 함께 혼합 널 (null)을 가지고,하지만 당신은 아이디어를 얻을 ...

+0

정말 고마워요! =) –