create table t1(계산품목 char(4), 계산품목그룹 char(10), 원금 int, 매상 int, 잔금 int)
go
insert into t1 values('현금','그룹1', 2, 1, 1)
insert into t1 values('이자','그룹1', 3, 2, 1)
insert into t1 values('사채','그룹2', 5, 3, 2)
insert into t1 values('채권','그룹2', 9, 5, 4)
insert into t1 values('증권','그룹3', 3, 3, 0)
insert into t1 values('금리','그룹3', 6, 1, 5)
go
-------------------------------------
원하는 결과
-------------------------------------
품목 원금액 매상액 잔금액
-------------------------------------
-------------------------------------
현금 2 1 1
이자 3 2 1
그룹1 5 3 2
-------------------------------------
사채 5 3 2
채권 9 5 4
그룹2 14 8 6
-------------------------------------
증권 3 3 0
금리 6 1 5
그룹3 9 4 5
-------------------------------------
Total 28 15 13
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, 'a' as sort union all select 2, 'b' union all select 3, 'c') y
group by case y.no when 1 then 계산품목+' '+convert(varchar(40), newid())
when 2 then 계산품목그룹
when 3 then 'Total' end
order by max(계산품목그룹 + y.sort), case y.no when 1 then 계산품목+' '+convert(varchar(40), newid())
when 2 then 계산품목그룹
when 3 then 'Total' end
이렇게도 소계을 구할수 있군요.
'SQL' 카테고리의 다른 글
| 버퍼 풀에서 빈 버퍼를 모두 제거합니다 (0) | 2007/06/07 |
|---|---|
| 심심풀이 15탄 (0) | 2007/06/07 |
| 소계 쿼리 (0) | 2007/06/07 |
| 심심풀이 13탄 (0) | 2007/06/07 |
| 심심풀이 14탄 (0) | 2007/06/07 |
| 심심풀이 13탄(2) (0) | 2007/06/07 |




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