select min(case y.no when 1 then 계산품목
when 2 then 계산품목그룹
when 3 then 'Total' end) 품목,
isnull(sum(원금),0) 원금액,
isnull(sum(매상),0) 매상액,
isnull(sum(잔금),0) 잔금액
from t1 x cross join (select '1' as no union all select '2' union all select '3') y
group by case y.no when 1 then 계산품목+' '+convert(varchar(40), newid())
when 2 then 계산품목그룹
when 3 then 'Total' end
order by min(case when y.no=3 then '3' else '1'+계산품목그룹+y.no end)
이렇게 하실수도 있지만
그렇지 않고 출력순서가 현금,이자,사채,채권,증권,금리
와 같이 고정되어 있다면 아래와 같이 추가적으로 정렬을 명시해주셔야 합니다.
select min(case y.no when 1 then 계산품목
when 2 then 계산품목그룹
when 3 then 'Total' end) 품목,
isnull(sum(원금),0) 원금액,
isnull(sum(매상),0) 매상액,
isnull(sum(잔금),0) 잔금액
from t1 x cross join (select '1' as no union all select '2' union all select '3') y
group by case y.no when 1 then 계산품목+' '+convert(varchar(40), newid())
when 2 then 계산품목그룹
when 3 then 'Total' end
order by min(case when y.no=3 then '3' else '1'+계산품목그룹+y.no end),
min(case 계산품목 when '현금' then 1
when '이자' then 2
when '사채' then 3
when '채권' then 4
when '증권' then 5
when '금리' then 6 end)
하지만, 지금과 같은 상황이라면 굳이 위와같이 하지 않고 rollup을 사용하셔도 될듯...
select case when grouping(계산품목그룹)=1 then 'Total'
when grouping(계산품목)=1 then 계산품목그룹 else 계산품목 end as 품목,
sum(원금), sum(매상), sum(잔금)
from t1
group by 계산품목그룹, 계산품목 with rollup
order by grouping(계산품목그룹),
계산품목그룹+str(grouping(계산품목)),
case 계산품목 when '현금' then 1
when '이자' then 2
when '사채' then 3
when '채권' then 4
when '증권' then 5
when '금리' then 6 end
'SQL' 카테고리의 다른 글
| 심심풀이 10탄 (0) | 2007/06/07 |
|---|---|
| 심심풀이 12탄 (0) | 2007/06/07 |
| cross join 이용한 그룹 집계 (0) | 2007/06/07 |
| 락 용어정리 (0) | 2007/06/07 |
| sp를 WITH ENCRYPTION 암호화 한거 풀기 (0) | 2007/06/07 |
| 심심풀이 5탄 (0) | 2007/06/07 |
0 Trackback,
0 Comment,
:




최근에 달린 댓글
링크
최근에 받은 트랙백
태그목록