SQL 질문과 답변 게시판
Microsoft SQL Server와 관련된 질문과 답변을 올리는 게시판입니다. 궁금하신 내용을 이곳에서 문의하시면 SQLER 분들의 답변을 받으실 수 있습니다. 문의를 하실때에는 최근 작업하신 특이 사항이나, 장애 발생 전 상황을 상세히 올려 주시면 답글을 적어주시는 SQLER분들의 답변이 더 정확할 수 있으니 도움 되시길 바랍니다. 쿼리 문의일 경우, 실제 문제가 재현되는 테이블생성, 샘플데이터 생성 쿼리를 함께 올려 주시면 더 빠르고 정확한 쿼리 문의 응답이 가능합니다.
글 수 5,167
--test table 생성
create table tblTmp(
idx int,
title char(3)
);
--데이타 넣기
insert into tblTmp( idx, title )
select 1, 'abc'
union all
select 2, 'def'
union all
select 3, 'gh '
;
-- #1 이렇게 땜빵은 했는데..
select idx, title
from ( select top 1 idx, title from tblTmp where idx < 2 order by idx desc ) AS aa
union all
select idx, title
from ( select top 1 idx, title from tblTmp where idx > 2 order by idx asc ) AS aa
-- #2 이게 왜 안되누
/*
select top 1 idx, title from tblTmp where idx < 2 order by idx desc
union all
select top 1 idx, title from tblTmp where idx < 2 order by idx desc;
*/
--test 테이블 지우기
drop table tblTmp;
/*
#2로 되어있는 부분이 왜 syntax error인지 당최 모르겠습니다.
초급은 살짝 넘지 않았나 생각했는데 당황스럽네요...
*/
2010.09.06 10:54:39 (*.252.142.126)
인라인뷰에 order by를 기술할때 top을 쓸때 허용합니다.
union 앞에는 order by를 허용하지 않는걸로 압니다.
select * from test order by 1
union all
select * from test order by 1 는 안되고
select * from test
union all
select * from test order by 1 은 됩지만 원하시는 소트는 아닐겁니다.
처음에 하셨던 방법이나 知音님 말씀처럼 각각의 select문에 별도 구분을 만들어 그걸 이용하시는 방법은 있구요.
with test as
(
select 1 n,2 m union all
select 2 n,2 m union all
select 3 n,2 m union all
select 4 n,2 m union all
select 5 n,2 m )
select '1' mm, * from test where n > 3
union all
select '2' mm, * from test where n < 3
order by mm
2010.09.06 09:04:59 (*.97.37.231)
order by 1 desc
union 이나 union all 로 묶인 경우 건우아빠님 말씀 처럼
order by 절에 select 절의 컬럼을 직접기술할 수 없고,
select 절에 나오는 순서대로 1,2,....,n 까지로 구분하여 처리가 가능합니다


union으로 묶을 때는 order by를 직접 기술할수 없습니다.